Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
classification_result = await classify_all_items(
unclassified,
group_definitions,
current_user=current_user,
batch_size=batch_size,
)
classifications = classification_result["classified_groups"]
# unique_items = [{v.id: v} for v in classifications.values()]
classification_failures = classification_result["failed_items"]
total_failed += len(classification_failures)
logger.info("")
for group_name, group_items in classifications.items():
# The LLM functions have aggregated item IDs into groups.
# But now we need to match the group names to output feeds and put the items
# into the DB.
# We're matching based on name because the LLM isn't given IDs.
# We can be confident that the name is unique in the catalogue.
logger.debug(
f"Trying to find an output feed called '{group_name}' to match it to the "
"LLM response",
extra={"group_name": group_name},
)
output_feed = next(
(feed for feed in output_feeds if feed.title == group_name), None
)
if not output_feed:
logger.error(
f"LLM gave name {group_name}, but it's not an output feed.",
extra={"group_name": group_name},
)
# All items in this group are consequently failed
total_failed += len(group_items)
continue
logger.debug(f"Found an output feed called '{group_name}', now matching items")
for llm_item in group_items:
db_item = next(
(item for item in unclassified if item.id == llm_item.id),
None,
)
if db_item:
await session.refresh(db_item)
existing_classifications_result = await session.exec(
select(ItemFeedLink).where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
)
existing_classifications = existing_classifications_result.all()
if existing_classifications:
logger.warning(
"Surprised to find at least one existing classification",
extra={
"item_id": db_item.id,
"feed_id": existing_classifications.feed_id,
},
)
await session.delete(existing_classifications)
updated_classification = ItemFeedLink(
item_id=db_item.id, feed_id=output_feed.id
)
session.add(updated_classification)
classified_group_counts[group_name] += 1
total_classified += 1
else:
logger.error(
f"Couldn't find item with id {llm_item.id}",
extra={"item_id": llm_item.id},
)
total_failed += 1
await session.commit()
Does this SQLAlchemy session management work the way I think it does? I am specifically concerned about IntegrityErrors
Your code snippet involves SQLAlchemy session management, and you're concerned about IntegrityErrors, which typically occur due to database constraint violations (e.g., unique constraints, foreign key constraints, etc.). Let's analyze your code step by step to evaluate the session management and potential risks of IntegrityErrors, and then provide recommendations to improve robustness.
Classification Process:
classification_result containing classified_groups (a dictionary mapping group names to lists of items) and failed_items.output_feeds, and process items within each group.Database Operations:
unclassified list (db_item).ItemFeedLink records for the item.ItemFeedLink to associate the item with the matched output_feed.await session.commit().Error Handling:
total_failed when:
output_feed cannot be found for a group name.llm_item) cannot be matched to a db_item in unclassified.Your session management appears to follow SQLAlchemy's best practices for async operations, but there are a few areas where IntegrityErrors or other issues could arise. Let's break this down:
session object for the entire operation, and you commit changes at the end with await session.commit(). This is generally a good practice because it ensures that all changes are applied atomically (i.e., either all succeed or all fail).IntegrityError occurs during commit, the entire transaction will be rolled back, and none of the changes (e.g., deletions or insertions) will be applied. This is the desired behavior for atomicity, but it means you need to handle such errors explicitly if you want to recover gracefully.This currently sits within a loop:
@app.post("/catalogue/classified")
async def classify_all_catalogues(
paid_tier_only: bool = True,
current_user: user = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
if not is_admin(current_user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You can only classify your own catalogues",
)
# TODO: Randomise the order
if paid_tier_only:
# Get paid tier users with active subscriptions
paid_tier_users_result = await session.exec(
select(user)
.join(Subscription)
.where(
Subscription.status.in_(
[
SubscriptionStatus.ACTIVE,
SubscriptionStatus.TRIALING,
SubscriptionStatus.PAST_DUE,
]
),
Subscription.end_date > datetime.now(UTC),
)
.distinct()
)
paid_tier_users = paid_tier_users_result.all()
# Get catalogues from paid tier users
catalogues_result = await session.exec(
select(Catalogue).where(
Catalogue.user_id.in_([user.id for user in paid_tier_users])
)
)
catalogues = catalogues_result.all()
logger.debug(
f"Classifying {len(catalogues)} catalogues for paid tier users",
extra={"catalogues": [catalogue.id for catalogue in catalogues]},
)
else:
catalogues_result = await session.exec(select(Catalogue))
catalogues = catalogues_result.all()
logger.debug(
f"Classifying {len(catalogues)} catalogues",
extra={"catalogues": [catalogue.id for catalogue in catalogues]},
)
for catalogue in catalogues:
try:
await classify_catalogue(
catalogue.id, current_user=current_user, session=session
)
except Exception as err:
logger.critical(
f"Unexpected error classifying catalogue {catalogue.id}: {err}",
exc_info=True,
)
continue
return {"message": f"Classified {len(catalogues)} catalogues"}
What are the implications of doing the session.commit() / session.rollback() now?
Your code is now structured such that the classification logic (including the database operations and session management) is embedded within a loop over multiple catalogues, and the session is managed at a higher level (in the classify_all_catalogues endpoint). The changes I suggested in the previous response, particularly around session.commit() and session.rollback(), have implications in this context. Let's analyze these implications and provide recommendations to ensure robust session management, error handling, and database consistency.
Session Scope:
AsyncSession object (session) is passed into the endpoint via dependency injection (Depends(get_session)). This session is shared across all catalogues processed in the loop.classify_catalogue (which contains the classification logic and database operations) uses this shared session.classify_all_catalogues function; instead, commits and rollbacks are handled within classify_catalogue (or deeper, in the process_classifications function, as per the revised code).Loop Behavior:
classify_catalogue for each one.continue).Transaction Management:
session.commit() is called for each item within a catalogue (or potentially for each group, depending on the granularity of your transaction management).IntegrityError or other exception occurs, session.rollback() is called to undo changes for that specific item (or group).session.commit() and session.rollback() in This ContextSince the same session object is used for all catalogues, the state of the session (e.g., pending changes, object cache) persists across iterations of the loop. This has several implications:
Pending Changes:
You query for existing ItemFeedLink records with:
existing_classifications_result = await session.exec(
select(ItemFeedLink).where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
)
existing_classifications = existing_classifications_result.all()
Then, if any exist, you delete them with:
if existing_classifications:
await session.delete(existing_classifications)
Issue: existing_classifications is a list of ItemFeedLink objects, but session.delete() expects a single object, not a list. This will raise a TypeError or fail silently depending on your SQLAlchemy version. To fix this, you need to iterate over the list and delete each object individually, or use a bulk delete operation.
Fix:
if existing_classifications:
for classification in existing_classifications:
await session.delete(classification)
ItemFeedLink with:
updated_classification = ItemFeedLink(
item_id=db_item.id, feed_id=output_feed.id
)
session.add(updated_classification)
IntegrityError: If ItemFeedLink has a unique constraint on (item_id, feed_id) (which is common for association tables), and an existing record with the same (item_id, feed_id) exists in the database, the commit will fail with an IntegrityError. Your code attempts to mitigate this by deleting existing classifications, but there are edge cases to consider:
ItemFeedLink table between your select and commit, you could still encounter an IntegrityError.feed_id.in_([feed.id for feed in output_feeds]) filter), you might miss some records, leading to a constraint violation.await session.commit(). If an IntegrityError occurs here, the entire transaction is rolled back, and none of the changes (deletions or insertions) are applied. However, your code does not currently handle this rollback explicitly, so the error will propagate up the call stack, potentially crashing the application or leaving it in an inconsistent state (e.g., total_classified and total_failed counters might be incorrect).IntegrityErrorHere are the specific risks of IntegrityError in your code:
Unique Constraint Violations:
ItemFeedLink has a unique constraint on (item_id, feed_id), and you attempt to insert a duplicate record, an IntegrityError will occur. Your deletion logic attempts to prevent this, but it might not cover all cases (e.g., race conditions or incomplete deletion).Foreign Key Constraint Violations:
item_id or feed_id in ItemFeedLink references a non-existent Item or Feed in the database, an IntegrityError will occur. This could happen if:
db_item.id or output_feed.id is invalid or has been deleted by another process.unclassified list or output_feeds contains stale data.Race Conditions:
ItemFeedLink records, leading to race conditions. For example:
ItemFeedLink and adds a new one.IntegrityError due to the unique constraint.Uncommitted Changes:
IntegrityError occurs during commit, the session is rolled back, but your counters (total_classified, total_failed) and logs might not reflect this rollback, leading to inconsistent state tracking.IntegrityErrorsTo make your code more robust and handle IntegrityErrors effectively, consider the following improvements:
As mentioned earlier, session.delete() does not accept a list. Fix this by iterating over the list or using a bulk delete operation.
Option 1: Iterate Over List:
if existing_classifications:
for classification in existing_classifications:
await session.delete(classification)
Option 2: Use Bulk Delete (more efficient for large lists):
if existing_classifications:
await session.exec(
delete(ItemFeedLink).where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
)
IntegrityError During CommitWrap the commit in a try-except block to catch IntegrityErrors and handle them gracefully. For example, you might want to log the error, roll back the transaction, and update your counters accordingly.
Example:
from sqlalchemy.exc import IntegrityError
try:
await session.commit()
except IntegrityError as e:
await session.rollback()
logger.error(f"IntegrityError during commit: {str(e)}")
# Mark all items in this batch as failed
total_failed += sum(len(items) for items in classifications.values())
total_classified = 0 # Reset classified count since the transaction failed
raise # Re-raise the exception if you want to propagate it, or handle it silently
To mitigate race conditions, consider using database-level locking or optimistic concurrency control. For example, you can use SELECT ... FOR UPDATE to lock the rows you're modifying, ensuring that no other process can modify them until your transaction is complete.
Example (using FOR UPDATE):
existing_classifications_result = await session.exec(
select(ItemFeedLink)
.where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
.with_for_update() # Lock the rows
)
existing_classifications = existing_classifications_result.all()
Note: with_for_update() is not supported by all databases (e.g., SQLite in some configurations), so ensure your database supports it.
Alternatively, you can use a more robust approach by performing an "upsert" (insert or update) operation, which avoids the need to delete and re-insert records. For example, you can use SQLAlchemy's on_conflict_do_update (for PostgreSQL) or a similar mechanism for your database.
Before adding a new ItemFeedLink, ensure that item_id and feed_id reference valid records in the Item and Feed tables. You can do this by querying the database or validating the data in unclassified and output_feeds.
Example:
# Validate item_id
item_exists = await session.get(Item, db_item.id)
if not item_exists:
logger.error(f"Item with id {db_item.id} does not exist in the database")
total_failed += 1
continue
# Validate feed_id
feed_exists = await session.get(Feed, output_feed.id)
if not feed_exists:
logger.error(f"Feed with id {output_feed.id} does not exist in the database")
total_failed += 1
continue
Instead of committing all changes at the end, consider committing changes for each group or even each item. This reduces the risk of a single failure rolling back all changes, but it sacrifices atomicity. Use this approach only if partial success is acceptable in your use case.
Example (commit per group):
for group_name, group_items in classifications.items():
try:
# Process items in the group
output_feed = next(
(feed for feed in output_feeds if feed.title == group_name), None
)
if not output_feed:
logger.error(
f"LLM gave name {group_name}, but it's not an output feed.",
extra={"group_name": group_name},
)
total_failed += len(group_items)
continue
for llm_item in group_items:
db_item = next(
(item for item in unclassified if item.id == llm_item.id),
None,
)
if db_item:
await session.refresh(db_item)
existing_classifications_result = await session.exec(
select(ItemFeedLink).where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
)
existing_classifications = existing_classifications_result.all()
if existing_classifications:
for classification in existing_classifications:
await session.delete(classification)
updated_classification = ItemFeedLink(
item_id=db_item.id, feed_id=output_feed.id
)
session.add(updated_classification)
classified_group_counts[group_name] += 1
total_classified += 1
else:
logger.error(
f"Couldn't find item with id {llm_item.id}",
extra={"item_id": llm_item.id},
)
total_failed += 1
# Commit changes for this group
await session.commit()
except IntegrityError as e:
await session.rollback()
logger.error(f"IntegrityError for group {group_name}: {str(e)}")
total_failed += len(group_items)
continue
Ensure that your counters (total_classified, total_failed) and logs accurately reflect the state of the database. For example, if a transaction is rolled back, you should not increment total_classified.
Example:
if db_item:
try:
await session.refresh(db_item)
existing_classifications_result = await session.exec(
select(ItemFeedLink).where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
)
existing_classifications = existing_classifications_result.all()
if existing_classifications:
for classification in existing_classifications:
await session.delete(classification)
updated_classification = ItemFeedLink(
item_id=db_item.id, feed_id=output_feed.id
)
session.add(updated_classification)
await session.commit() # Commit immediately for this item
classified_group_counts[group_name] += 1
total_classified += 1
except IntegrityError as e:
await session.rollback()
logger.error(f"IntegrityError for item {db_item.id}: {str(e)}")
total_failed += 1
else:
logger.error(
f"Couldn't find item with id {llm_item.id}",
extra={"item_id": llm_item.id},
)
total_failed += 1
Here’s a revised version of your code incorporating the above recommendations:
from sqlalchemy.exc import IntegrityError
from sqlalchemy import select, delete
async def process_classifications(
classifications,
unclassified,
output_feeds,
session,
classified_group_counts,
total_classified,
total_failed,
logger,
):
for group_name, group_items in classifications.items():
logger.debug(
f"Trying to find an output feed called '{group_name}' to match it to the LLM response",
extra={"group_name": group_name},
)
output_feed = next(
(feed for feed in output_feeds if feed.title == group_name), None
)
if not output_feed:
logger.error(
f"LLM gave name {group_name}, but it's not an output feed.",
extra={"group_name": group_name},
)
total_failed += len(group_items)
continue
logger.debug(f"Found an output feed called '{group_name}', now matching items")
for llm_item in group_items:
db_item = next(
(item for item in unclassified if item.id == llm_item.id),
None,
)
if not db_item:
logger.error(
f"Couldn't find item with id {llm_item.id}",
extra={"item_id": llm_item.id},
)
total_failed += 1
continue
try:
# Validate foreign keys
item_exists = await session.get(Item, db_item.id)
if not item_exists:
logger.error(f"Item with id {db_item.id} does not exist in the database")
total_failed += 1
continue
feed_exists = await session.get(Feed, output_feed.id)
if not feed_exists:
logger.error(f"Feed with id {output_feed.id} does not exist in the database")
total_failed += 1
continue
# Refresh db_item to ensure it's up-to-date
await session.refresh(db_item)
# Delete existing classifications
existing_classifications_result = await session.exec(
select(ItemFeedLink)
.where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
.with_for_update() # Lock rows to prevent race conditions
)
existing_classifications = existing_classifications_result.all()
if existing_classifications:
for classification in existing_classifications:
await session.delete(classification)
# Add new classification
updated_classification = ItemFeedLink(
item_id=db_item.id, feed_id=output_feed.id
)
session.add(updated_classification)
# Commit changes for this item
await session.commit()
# Update counters
classified_group_counts[group_name] += 1
total_classified += 1
except IntegrityError as e:
await session.rollback()
logger.error(f"IntegrityError for item {db_item.id}: {str(e)}")
total_failed += 1
except Exception as e:
await session.rollback()
logger.error(f"Unexpected error for item {db_item.id}: {str(e)}")
total_failed += 1
return total_classified, total_failed
# Usage in your main function
classification_result = await classify_all_items(
unclassified,
group_definitions,
current_user=current_user,
batch_size=batch_size,
)
classifications = classification_result["classified_groups"]
classification_failures = classification_result["failed_items"]
total_failed += len(classification_failures)
logger.info("")
total_classified, total_failed = await process_classifications(
classifications,
unclassified,
output_feeds,
session,
classified_group_counts,
total_classified,
total_failed,
logger,
)
Your SQLAlchemy session management is generally sound, but there are risks of IntegrityErrors due to unique constraints, foreign key constraints, and race conditions. The key improvements to address these risks are:
IntegrityErrors during commit with try-except blocks and rollbacks.By implementing these changes, you can make your code more robust and resilient to IntegrityErrors and other database-related issues.
session.commit() is not called (or fails) for one catalogue, any pending changes (e.g., added ItemFeedLink objects) remain in the session's pending state. These changes could interfere with the processing of subsequent catalogues, potentially leading to unexpected behavior or errors.ItemFeedLink is added to the session but not committed (due to an error and rollback), it might still be in the session's object cache, causing issues when processing the next catalogue.Object Cache:
Item, Feed, or ItemFeedLink objects are loaded or modified across multiple catalogues, the session might return stale or inconsistent data unless you explicitly refresh or evict objects.Item is modified in one catalogue and not committed, the session might return the modified (but uncommitted) version of the Item when processing the next catalogue.Transaction Scope:
session.commit() creates a new transaction boundary. If you commit changes for individual items or groups within a catalogue, the changes for that catalogue are persisted to the database, even if subsequent catalogues fail. This means that the processing of catalogues is not atomic—some catalogues might be fully classified, while others might fail, leaving the system in a partially updated state.session.rollback(), it undoes all uncommitted changes in the session, including changes from previous catalogues that were not yet committed. This could lead to unintended rollbacks of successful operations.Granularity of Rollbacks:
session.rollback() is called for individual items (or groups) within a catalogue when an IntegrityError occurs. This is fine for isolating failures within a catalogue, but it does not undo changes that were already committed for previous items or groups within the same catalogue.Uncaught Exceptions:
classify_catalogue that is not caught within the function (e.g., a database connection error, a programming error, or an unhandled IntegrityError), the exception will propagate up to the try-except block in classify_all_catalogues. The loop will continue to the next catalogue, but the session might be left in an inconsistent state (e.g., with pending changes or a broken transaction).classify_catalogue using the same session will fail, potentially causing the entire endpoint to fail.Session Overhead:
session.commit() calls (e.g., for each item or group) can also introduce performance overhead, as each commit involves a database round-trip and potentially triggers database triggers, constraints, or indexes.Database Locks:
with_for_update() (as suggested in the revised code) to prevent race conditions, database locks might be held for the duration of the session, potentially causing contention if other processes are accessing the same data. This is less of an issue if you commit frequently, but it could still impact performance in a high-concurrency environment.To address these implications and ensure robust session management, error handling, and database consistency, consider the following recommendations:
Instead of sharing a single session across all catalogues, create a new session for each catalogue. This isolates the processing of each catalogue, ensuring that errors in one catalogue do not affect others and that the session's state (e.g., pending changes, object cache) is reset for each catalogue.
Example:
@app.post("/catalogue/classified")
async def classify_all_catalogues(
paid_tier_only: bool = True,
current_user: user = Depends(get_current_user),
session_factory: AsyncSession = Depends(get_session), # Use session factory
):
if not is_admin(current_user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You can only classify your own catalogues",
)
# Fetch catalogues (as before)
if paid_tier_only:
paid_tier_users_result = await session_factory.exec(
select(user)
.join(Subscription)
.where(
Subscription.status.in_(
[
SubscriptionStatus.ACTIVE,
SubscriptionStatus.TRIALING,
SubscriptionStatus.PAST_DUE,
]
),
Subscription.end_date > datetime.now(UTC),
)
.distinct()
)
paid_tier_users = paid_tier_users_result.all()
catalogues_result = await session_factory.exec(
select(Catalogue).where(
Catalogue.user_id.in_([user.id for user in paid_tier_users])
)
)
catalogues = catalogues_result.all()
logger.debug(
f"Classifying {len(catalogues)} catalogues for paid tier users",
extra={"catalogues": [catalogue.id for catalogue in catalogues]},
)
else:
catalogues_result = await session_factory.exec(select(Catalogue))
catalogues = catalogues_result.all()
logger.debug(
f"Classifying {len(catalogues)} catalogues",
extra={"catalogues": [catalogue.id for catalogue in catalogues]},
)
successful_catalogues = 0
for catalogue in catalogues:
async with session_factory() as session: # Create a new session for each catalogue
try:
await classify_catalogue(
catalogue.id, current_user=current_user, session=session
)
successful_catalogues += 1
except Exception as err:
logger.critical(
f"Unexpected error classifying catalogue {catalogue.id}: {err}",
exc_info=True,
)
await session.rollback() # Roll back changes for this catalogue
continue
return {"message": f"Classified {successful_catalogues} out of {len(catalogues)} catalogues"}
Benefits:
Note: You'll need to modify your dependency injection to provide a session factory (e.g., AsyncSessionFactory) rather than a single session. For example, in FastAPI, you might define the dependency like this:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
engine = create_async_engine("your_database_url", echo=True)
async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_session():
async with async_session_factory() as session:
yield session
Within each catalogue, decide whether you want the classification to be atomic (all items classified or none). If atomicity is important, perform all database operations for a catalogue within a single transaction, committing only at the end of the catalogue's processing.
Example (atomic within each catalogue):
async def classify_catalogue(catalogue_id, current_user, session):
# Fetch catalogue, items, feeds, etc.
catalogue = await session.get(Catalogue, catalogue_id)
if not catalogue:
raise ValueError(f"Catalogue {catalogue_id} not found")
unclassified = await fetch_unclassified_items(catalogue, session) # Example function
output_feeds = await fetch_output_feeds(catalogue, session) # Example function
group_definitions = await fetch_group_definitions(catalogue, session) # Example function
classification_result = await classify_all_items(
unclassified,
group_definitions,
current_user=current_user,
batch_size=100, # Example batch size
)
classifications = classification_result["classified_groups"]
classification_failures = classification_result["failed_items"]
total_failed = len(classification_failures)
total_classified = 0
classified_group_counts = {feed.title: 0 for feed in output_feeds}
try:
total_classified, total_failed = await process_classifications(
classifications,
unclassified,
output_feeds,
session,
classified_group_counts,
total_classified,
total_failed,
logger,
)
await session.commit() # Commit all changes for this catalogue
except Exception as e:
await session.rollback() # Roll back all changes for this catalogue
logger.error(f"Error classifying catalogue {catalogue_id}: {str(e)}")
raise
logger.info(
f"Classified {total_classified} items, failed {total_failed} items for catalogue {catalogue_id}"
)
Benefits:
Drawbacks:
If partial success within a catalogue is acceptable (e.g., you want to classify as many items as possible, even if some fail), continue with the approach of committing changes for individual items or groups, as shown in the revised process_classifications function. However, ensure that the session is properly managed in case of errors.
Example (non-atomic within each catalogue):
async def process_classifications(
classifications,
unclassified,
output_feeds,
session,
classified_group_counts,
total_classified,
total_failed,
logger,
):
for group_name, group_items in classifications.items():
logger.debug(
f"Trying to find an output feed called '{group_name}' to match it to the LLM response",
extra={"group_name": group_name},
)
output_feed = next(
(feed for feed in output_feeds if feed.title == group_name), None
)
if not output_feed:
logger.error(
f"LLM gave name {group_name}, but it's not an output feed.",
extra={"group_name": group_name},
)
total_failed += len(group_items)
continue
logger.debug(f"Found an output feed called '{group_name}', now matching items")
for llm_item in group_items:
db_item = next(
(item for item in unclassified if item.id == llm_item.id),
None,
)
if not db_item:
logger.error(
f"Couldn't find item with id {llm_item.id}",
extra={"item_id": llm_item.id},
)
total_failed += 1
continue
try:
# Validate foreign keys
item_exists = await session.get(Item, db_item.id)
if not item_exists:
logger.error(f"Item with id {db_item.id} does not exist in the database")
total_failed += 1
continue
feed_exists = await session.get(Feed, output_feed.id)
if not feed_exists:
logger.error(f"Feed with id {output_feed.id} does not exist in the database")
total_failed += 1
continue
# Refresh db_item to ensure it's up-to-date
await session.refresh(db_item)
# Delete existing classifications
existing_classifications_result = await session.exec(
select(ItemFeedLink)
.where(
ItemFeedLink.item_id == db_item.id,
ItemFeedLink.feed_id.in_([feed.id for feed in output_feeds]),
)
.with_for_update() # Lock rows to prevent race conditions
)
existing_classifications = existing_classifications_result.all()
if existing_classifications:
for classification in existing_classifications:
await session.delete(classification)
# Add new classification
updated_classification = ItemFeedLink(
item_id=db_item.id, feed_id=output_feed.id
)
session.add(updated_classification)
# Commit changes for this item
await session.commit()
# Update counters
classified_group_counts[group_name] += 1
total_classified += 1
except IntegrityError as e:
await session.rollback()
logger.error(f"IntegrityError for item {db_item.id}: {str(e)}")
total_failed += 1
except Exception as e:
await session.rollback()
logger.error(f"Unexpected error for item {db_item.id}: {str(e)}")
total_failed += 1
return total_classified, total_failed
Benefits:
Drawbacks:
After an error occurs and session.rollback() is called, ensure that the session is in a usable state before continuing. In some cases (e.g., database connection errors), the session might become unusable, requiring a new session to be created. Using a new session for each catalogue (as recommended in point 1) mitigates this issue, but if you stick with a shared session, you should handle such errors explicitly.
Example (handling unusable sessions with a shared session):
@app.post("/catalogue/classified")
async def classify_all_catalogues(
paid_tier_only: bool = True,
current_user: user = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
if not is_admin(current_user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You can only classify your own catalogues",
)
# Fetch catalogues (as before)
# ...
successful_catalogues = 0
for catalogue in catalogues:
try:
await classify_catalogue(
catalogue.id, current_user=current_user, session=session
)
successful_catalogues += 1
except Exception as err:
logger.critical(
f"Unexpected error classifying catalogue {catalogue.id}: {err}",
exc_info=True,
)
await session.rollback() # Roll back changes for this catalogue
# Check if the session is still usable
try:
await session.exec(select(1)) # Test query to check session state
except Exception as session_err:
logger.error(f"Session is unusable after error: {session_err}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Database session error, please try again",
)
continue
return {"message": f"Classified {successful_catalogues} out of {len(catalogues)} catalogues"}
Note: This approach is less robust than using a new session for each catalogue, as it relies on the session remaining usable after errors.
To make it easier to track progress and recover from failures, consider adding a mechanism to record the classification status of each catalogue (e.g., in a database table or log). This can help you identify which catalogues were fully classified, partially classified, or not classified at all, and retry failed catalogues if needed.
Example (tracking classification status):
async def classify_catalogue(catalogue_id, current_user, session):
# Update catalogue status to "in progress"
catalogue = await session.get(Catalogue, catalogue_id)
if not catalogue:
raise ValueError(f"Catalogue {catalogue_id} not found")
catalogue.classification_status = "in_progress"
await session.commit()
try:
# Perform classification (as before)
# ...
# Update catalogue status to "completed"
catalogue.classification_status = "completed"
await session.commit()
except Exception as e:
# Update catalogue status to "failed"
catalogue.classification_status = "failed"
await session.commit()
logger.error(f"Error classifying catalogue {catalogue_id}: {str(e)}")
raise
Benefits:
If classifying all catalogues is a long-running operation, consider moving the processing to a background task (e.g., using Celery, RQ, or FastAPI's BackgroundTasks). This allows the endpoint to return immediately while the classification runs asynchronously, improving responsiveness and scalability.
Example (using FastAPI BackgroundTasks):
from fastapi import BackgroundTasks
@app.post("/catalogue/classified")
async def classify_all_catalogues(
paid_tier_only: bool = True,
background_tasks: BackgroundTasks = None,
current_user: user = Depends(get_current_user),
session_factory: AsyncSession = Depends(get_session),
):
if not is_admin(current_user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You can only classify your own catalogues",
)
# Fetch catalogues (as before)
# ...
background_tasks.add_task(process_catalogues_in_background, catalogues, current_user, session_factory)
return {"message": f"Started classification of {len(catalogues)} catalogues in the background"}
async def process_catalogues_in_background(catalogues, current_user, session_factory):
successful_catalogues = 0
for catalogue in catalogues:
async with session_factory() as session:
try:
await classify_catalogue(
catalogue.id, current_user=current_user, session=session
)
successful_catalogues += 1
except Exception as err:
logger.critical(
f"Unexpected error classifying catalogue {catalogue.id}: {err}",
exc_info=True,
)
await session.rollback()
continue
logger.info(f"Classified {successful_catalogues} out of {len(catalogues)} catalogues")
Benefits:
session.commit() / session.rollback()Shared Session:
Error Handling:
try-except block, but the session might become unusable after certain errors, causing subsequent catalogues to fail.Performance:
Use a New Session for Each Catalogue:
async_session_factory) to create new sessions.Decide on Atomicity Within Catalogues:
Handle Session State After Errors:
Track Progress:
Consider Background Processing:
By implementing these recommendations, you can ensure robust session management, error handling, and database consistency while processing multiple catalogues.