# runs.py: background runs (model replies, sub-agents, saves) tracked per item, locally and in Redis. import asyncio import logging from contextlib import suppress from itertools import groupby from uuid import uuid4 from redis.asyncio import Redis from redis.exceptions import RedisError from open_webui.env import REDIS_KEY_PREFIX, REDIS_RESPONSE_STREAM_TTL, REDIS_TASK_TTL from open_webui.utils.json_codec import JSONCodec, dumps_bytes from open_webui.utils.misc import get_output_text from open_webui.utils.response import get_response_delta_key, handle_responses_streaming_event log = logging.getLogger(__name__) # Active runs on this instance, by run id runs: dict[str, asyncio.Task] = {} item_runs = {} response_streams: dict[str, dict] = {} # The keys keep their old ':tasks' names, so runs in flight survive an upgrade. REDIS_RUNS_KEY = f'{REDIS_KEY_PREFIX}:tasks' REDIS_ITEM_RUNS_KEY = f'{REDIS_KEY_PREFIX}:tasks:item' REDIS_RESPONSE_STREAMS_KEY = f'{REDIS_KEY_PREFIX}:tasks:response_streams' REDIS_PUBSUB_CHANNEL = f'{REDIS_KEY_PREFIX}:tasks:commands' REDIS_PUBSUB_RECONNECT_INTERVAL = 1.0 REDIS_PUBSUB_MAX_RECONNECT_INTERVAL = 30.0 async def redis_run_command_listener(app): redis: Redis = app.state.redis reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL while True: pubsub = None try: # RedisCluster can't route a pubsub subscribe until initialize() fills its slot cache. await redis.initialize() pubsub = redis.pubsub() await pubsub.subscribe(REDIS_PUBSUB_CHANNEL) reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL async for message in pubsub.listen(): if message['type'] != 'message': continue try: command = JSONCodec.loads(message['data']) if command.get('action') != 'stop': continue local_run = runs.get(command.get('run_id')) if local_run: local_run.cancel() except Exception as e: log.exception(f'Error handling distributed run command: {e}') log.warning('Redis run command listener stopped. Retrying.') except asyncio.CancelledError: raise except Exception as e: log.exception(f'Redis run command listener failed. Retrying: {e}') finally: if pubsub: with suppress(Exception): await pubsub.aclose() await asyncio.sleep(reconnect_interval) reconnect_interval = min(reconnect_interval * 2, REDIS_PUBSUB_MAX_RECONNECT_INTERVAL) async def redis_run_heartbeat(app): redis: Redis = app.state.redis while True: await asyncio.sleep(REDIS_TASK_TTL / 4) try: pipe = redis.pipeline(transaction=False) for run_id in list(runs): # EXPIRE cannot recreate a run already removed by cleanup. pipe.expire(f'{REDIS_RUNS_KEY}:{run_id}', REDIS_TASK_TTL) await pipe.execute() except Exception: log.exception('Redis run heartbeat failed') # Redis-enabled handlers async def redis_save_run(redis: Redis, run_id: str, item_id: str | None): pipe = redis.pipeline(transaction=False) pipe.set(f'{REDIS_RUNS_KEY}:{run_id}', '1', ex=REDIS_TASK_TTL or None) pipe.hset(REDIS_RUNS_KEY, run_id, item_id or '') if item_id: pipe.sadd(f'{REDIS_ITEM_RUNS_KEY}:{item_id}', run_id) await pipe.execute() async def redis_cleanup_run(redis: Redis, run_id: str, item_id: str | None): pipe = redis.pipeline(transaction=False) pipe.delete(f'{REDIS_RUNS_KEY}:{run_id}') pipe.hdel(REDIS_RUNS_KEY, run_id) pipe.hdel(REDIS_RESPONSE_STREAMS_KEY, run_id) pipe.delete(f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}') if item_id: pipe.srem(f'{REDIS_ITEM_RUNS_KEY}:{item_id}', run_id) await pipe.execute() async def redis_list_runs(redis: Redis, item_id: str | None = None) -> list[str]: run_ids = list( await redis.smembers(f'{REDIS_ITEM_RUNS_KEY}:{item_id}') if item_id is not None else await redis.hkeys(REDIS_RUNS_KEY) ) if not run_ids or REDIS_TASK_TTL == 0: return run_ids pipe = redis.pipeline(transaction=False) for run_id in run_ids: pipe.exists(f'{REDIS_RUNS_KEY}:{run_id}') active = [] for run_id, exists in zip(run_ids, await pipe.execute()): if exists: active.append(run_id) else: run_item_id = item_id if item_id is not None else await redis.hget(REDIS_RUNS_KEY, run_id) await redis_cleanup_run(redis, run_id, run_item_id or None) return active async def redis_send_command(redis: Redis, command: dict): command_json = dumps_bytes(command) # RedisCluster doesn't expose publish() directly, but the # PUBLISH command broadcasts across all cluster nodes server-side. if hasattr(redis, 'nodes_manager'): await redis.execute_command('PUBLISH', REDIS_PUBSUB_CHANNEL, command_json) else: await redis.publish(REDIS_PUBSUB_CHANNEL, command_json) async def cleanup_run(redis, run_id: str, id=None): """ Remove a completed or canceled run from the global `runs` dictionary. """ if redis: await redis_cleanup_run(redis, run_id, id) runs.pop(run_id, None) # Remove the run if it exists response_streams.pop(run_id, None) # If an ID is provided, remove the run from the item_runs dictionary if id and run_id in item_runs.get(id, []): item_runs[id].remove(run_id) if not item_runs[id]: # If no runs left for this ID, remove the entry item_runs.pop(id, None) async def create_run(redis, coroutine, id=None, run_id=None): """ Start a coroutine as a run and add it to the global runs dictionary. """ run_id = run_id or str(uuid4()) # Generate a unique ID for the run task = asyncio.create_task(coroutine) # Create the task # Give the task a checkout routine before handing it the keys. task.add_done_callback(lambda t: asyncio.create_task(cleanup_run(redis, run_id, id))) runs[run_id] = task # File this run under its item ID, if it came with a return address. if id: if item_runs.get(id): item_runs[id].append(run_id) else: item_runs[id] = [run_id] if redis: await redis_save_run(redis, run_id, id) return run_id, task async def list_runs(redis): """ List all currently active run IDs. """ if redis: return await redis_list_runs(redis) return list(runs.keys()) async def list_run_ids_by_item_id(redis, id): """ List all runs associated with a specific ID. """ if redis: return await redis_list_runs(redis, id) return list(item_runs.get(id, [])) async def save_response_stream( redis, run_id: str | None, chat_id: str | None, message_id: str | None, output: list, ) -> int: """Save a snapshot and return its byte size; zero means it needs to be retried.""" if not run_id or not chat_id or not message_id: return 0 data = { 'chat_id': chat_id, 'message_id': message_id, 'output': output, } if redis: snapshot = dumps_bytes(data) + b'\n' try: await redis.set( f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}', snapshot, ex=REDIS_RESPONSE_STREAM_TTL if REDIS_RESPONSE_STREAM_TTL > 0 else None, ) except RedisError: return 0 return len(snapshot) else: response_streams[run_id] = data return 0 async def append_response_stream(redis: Redis, run_id: str, delta: bytes, size: int) -> bool: """Append only to the snapshot we last wrote, including after a Redis retry.""" try: return bool( await redis.eval( "if redis.call('strlen', KEYS[1]) ~= tonumber(ARGV[1]) then return 0 end " "redis.call('append', KEYS[1], ARGV[2]) " "if tonumber(ARGV[3]) > 0 then redis.call('expire', KEYS[1], ARGV[3]) end return 1", 1, f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}', size, delta, REDIS_RESPONSE_STREAM_TTL, ) ) except RedisError: return False def load_response_stream(value: str | bytes) -> dict: lines = value.split(b'\n' if isinstance(value, bytes) else '\n') snapshot, *deltas = (JSONCodec.loads(line) for line in lines if line) # Join adjacent text deltas before applying them, avoiding a full text copy per token. for _, events in groupby(deltas, key=get_response_delta_key): first, *rest = events delta = {**first, 'delta': first['delta'] + ''.join(event['delta'] for event in rest)} snapshot['output'], _ = handle_responses_streaming_event(delta, snapshot['output']) return snapshot async def get_response_streams_by_chat_id(redis, chat_id: str) -> list[dict]: run_ids = await list_run_ids_by_item_id(redis, chat_id) if not run_ids: return [] if redis: pipe = redis.pipeline(transaction=False) for run_id in run_ids: pipe.get(f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}') values = await pipe.execute() # Replies started on older instances still use the shared hash during an upgrade. if any(value is None for value in values): legacy = await redis.hmget(REDIS_RESPONSE_STREAMS_KEY, run_ids) values = [value if value is not None else old for value, old in zip(values, legacy)] streams = [] for value in values: if not value: continue try: data = load_response_stream(value) except Exception: continue if data.get('chat_id') == chat_id: data['content'] = get_output_text(data['output']) streams.append(data) return streams return [ {**stream, 'content': get_output_text(stream['output'])} for run_id in run_ids if (stream := response_streams.get(run_id)) and stream.get('chat_id') == chat_id ] async def clear_response_stream(redis, run_id: str | None): if not run_id: return if redis: pipe = redis.pipeline(transaction=False) pipe.delete(f'{REDIS_RESPONSE_STREAMS_KEY}:{run_id}') pipe.hdel(REDIS_RESPONSE_STREAMS_KEY, run_id) await pipe.execute() else: response_streams.pop(run_id, None) async def stop_run(redis, run_id: str): """ Cancel a run and remove it from the global run list. """ if redis: # Look up the item_id before cleanup so we can remove the set entry too item_id = await redis.hget(REDIS_RUNS_KEY, run_id) # PUBSUB: All instances check if they have this run, and stop if so. await redis_send_command( redis, { 'action': 'stop', 'run_id': run_id, }, ) # Always clean Redis directly — hdel/srem are idempotent, safe even # if the done_callback on the owning process also fires cleanup. await redis_cleanup_run(redis, run_id, item_id or None) return {'status': True, 'message': f'Run {run_id} stopped.'} task = runs.pop(run_id, None) if not task: return {'status': False, 'message': f'Run with ID {run_id} not found.'} task.cancel() # Request task cancellation try: await task # Wait for the task to handle the cancellation except asyncio.CancelledError: # Run successfully canceled return {'status': True, 'message': f'Run {run_id} successfully stopped.'} if task.cancelled() or task.done(): return {'status': True, 'message': f'Run {run_id} successfully cancelled.'} return {'status': True, 'message': f'Cancellation requested for {run_id}.'} async def stop_item_runs(redis: Redis, item_id: str): """ Stop all runs associated with a specific item ID. """ run_ids = await list_run_ids_by_item_id(redis, item_id) if not run_ids: return {'status': True, 'message': f'No runs found for item {item_id}.'} # Cleanup mutates the local run list while cancellation is awaited. for run_id in list(run_ids): # A run that already finished needs no stopping; continue with the rest. await stop_run(redis, run_id) return {'status': True, 'message': f'All runs for item {item_id} stopped.'} async def has_active_runs(redis, chat_id: str) -> bool: """Check if a chat has any active runs.""" run_ids = await list_run_ids_by_item_id(redis, chat_id) return len(run_ids) > 0