Add user_initiated flag to RequestContext for async task attribution (#338)

Async batch retain tasks need internal=True to bypass extension auth
(worker has no API key), but extensions also need to know the operation
originated from a user request. The new user_initiated flag on
RequestContext allows extensions to distinguish user-initiated async
operations from truly internal system operations like consolidation.
This commit is contained in:
Chris Bartholomew 2026-02-10 16:37:42 -05:00 committed by GitHub
parent 6eec83b20d
commit 90be7c6829
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 9 additions and 5 deletions

View file

@ -545,16 +545,19 @@ class MemoryEngine(MemoryEngineInterface):
f"[BATCH_RETAIN_TASK] Starting background batch retain for bank_id={bank_id}, {len(contents)} items" f"[BATCH_RETAIN_TASK] Starting background batch retain for bank_id={bank_id}, {len(contents)} items"
) )
# Restore tenant_id/api_key_id from task payload so downstream operations # Restore tenant_id/api_key_id from task payload so extensions
# (e.g., consolidation and mental model refreshes) can attribute usage. # (e.g., operation validators) can attribute the operation correctly.
# internal=True to skip extension auth (worker has no API key),
# user_initiated=True so extensions know this originated from a user request.
from hindsight_api.models import RequestContext from hindsight_api.models import RequestContext
internal_context = RequestContext( context = RequestContext(
internal=True, internal=True,
user_initiated=True,
tenant_id=task_dict.get("_tenant_id"), tenant_id=task_dict.get("_tenant_id"),
api_key_id=task_dict.get("_api_key_id"), api_key_id=task_dict.get("_api_key_id"),
) )
await self.retain_batch_async(bank_id=bank_id, contents=contents, request_context=internal_context) await self.retain_batch_async(bank_id=bank_id, contents=contents, request_context=context)
logger.info(f"[BATCH_RETAIN_TASK] Completed background batch retain for bank_id={bank_id}") logger.info(f"[BATCH_RETAIN_TASK] Completed background batch retain for bank_id={bank_id}")

View file

@ -20,7 +20,8 @@ class RequestContext:
api_key: str | None = None api_key: str | None = None
api_key_id: str | None = None # UUID of the API key used for authentication api_key_id: str | None = None # UUID of the API key used for authentication
tenant_id: str | None = None # Tenant identifier (set by extension after auth) tenant_id: str | None = None # Tenant identifier (set by extension after auth)
internal: bool = False # True for background/internal operations (not user-visible) internal: bool = False # True for background/internal operations (skips extension auth)
user_initiated: bool = False # True for async operations that originated from a user request
from pgvector.sqlalchemy import Vector from pgvector.sqlalchemy import Vector