---
name: kimaai_chatbot_session_retention_after_cleanup
type: action
since: 1.4.9
tier: free
feature: chat-history
area: chatbot
summary: Fires after a run of the cleanup of old chatbot conversations, with what it deleted.
parameters:
  - name: after_context
    type: array
    description: The context of the run (source, settings, mode, effectiveDays, cutoffTimestamp) with deletedCounts, the rows per table, and error, the message of a failed batch or empty.
---

# kimaai_chatbot_session_retention_after_cleanup

## When it fires

At the end of every run of the conversation cleanup that went ahead, after the lock was released: also when there was nothing to delete, and also when a batch failed. A failed batch is rolled back and ends the run; `error` holds its message and the next run tries again.

`deletedCounts` adds up all batches: `sessionsDeleted` (conversations), `chatRowsDeleted` (messages), `feedbackRowsDeleted`, `csatRowsDeleted`, `adminFeedbackMessageRowsDeleted`, `adminFeedbackCsatRowsDeleted`, `sessionFactRowsDeleted`, `questionTopicRowsDeleted`, `toolAuditRowsDeleted`, `conversionRowsUnlinked`, `orderLinksRemoved` and `batchesProcessed`.

## Example

```php
add_action(
  'kimaai_chatbot_session_retention_after_cleanup',
  function (array $context): void {
    $deleted = (int) $context['deletedCounts']['sessionsDeleted'];
    if ($deleted === 0 && $context['error'] === '') {
      return;
    }

    wp_mail(
      get_option('admin_email'),
      'Old chatbot conversations',
      $context['error'] !== ''
        ? 'The cleanup stopped: ' . $context['error']
        : sprintf('%d conversations older than %d days were deleted.', $deleted, $context['effectiveDays'])
    );
  }
);
```

## Related

- `kimaai_chatbot_session_retention_before_cleanup`: fires before the run deletes anything.
- `kimaai_chatbot_session_retention_days`: the retention period.
