Skip to content

Commit f24ee43

Browse files
mrveissclaude
andauthored
tech-debt(constants): replace asyncio.sleep() magic numbers with TimingConstants (#3549) (#3556)
Adds YIELD_INTERVAL, FAST_POLL_INTERVAL, DEBOUNCE_INTERVAL_S, and SESSION_CLEANUP_INTERVAL to TimingConstants. Migrates 29 production files off raw float/int literals in asyncio.sleep() calls. Excludes asyncio.sleep(0) yields (semantically must be 0), computed expressions, and test files. Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent d0c2162 commit f24ee43

34 files changed

Lines changed: 87 additions & 49 deletions

autobot-backend/agents/base_agent.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from typing import Any, Dict, List, Optional
1919

2020
# Import communication protocol
21+
from constants.threshold_constants import TimingConstants
2122
from protocols.agent_communication import (
2223
AgentIdentity,
2324
MessageHeader,
@@ -223,7 +224,7 @@ async def health_check(self) -> AgentHealth:
223224

224225
async def _ping(self) -> bool:
225226
"""Basic connectivity test - can be overridden by subclasses"""
226-
await asyncio.sleep(0.001) # Simulate minimal processing
227+
await asyncio.sleep(TimingConstants.YIELD_INTERVAL) # Simulate minimal processing
227228
return True
228229

229230
async def _get_resource_usage(self) -> Dict[str, Any]:

autobot-backend/ai_hardware_accelerator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -854,7 +854,7 @@ async def _gpu_semantic_search(self, input_data: Dict[str, Any]) -> Dict[str, An
854854
async def _process_on_cpu(self, task: ProcessingTask) -> Dict[str, Any]:
855855
"""Process task on CPU (fallback)."""
856856
# Basic CPU processing fallback
857-
await asyncio.sleep(0.1) # Simulate processing
857+
await asyncio.sleep(TimingConstants.MICRO_DELAY) # Simulate processing
858858

859859
return {
860860
"result": f"CPU processed task {task.task_type}",

autobot-backend/api/codebase_analytics/indexing_phases.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
import logging
2020
from typing import Callable, Optional
2121

22+
from constants.threshold_constants import TimingConstants
23+
2224
from .chromadb_storage import (
2325
_initialize_chromadb_collection,
2426
_prepare_batch_data,
@@ -73,7 +75,7 @@ async def _init_chromadb_with_retry(
7375
)
7476
if not code_collection:
7577
logger.warning("[Task %s] ChromaDB init failed, retrying once (#1249)", task_id)
76-
await asyncio.sleep(2)
78+
await asyncio.sleep(TimingConstants.SERVICE_STARTUP_DELAY)
7779
code_collection = await _initialize_chromadb_collection(
7880
task_id, update_progress, update_phase, source_id=source_id
7981
)

autobot-backend/api/log_forwarding.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from auth_middleware import check_admin_permission
2929
from autobot_shared.error_boundaries import ErrorCategory, with_error_handling
3030
from autobot_shared.ssot_config import config
31+
from constants.threshold_constants import TimingConstants
3132

3233
# Add scripts path for log forwarder import
3334
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
@@ -607,7 +608,7 @@ async def start_forwarding(
607608
thread.start()
608609

609610
# Wait briefly for startup
610-
await asyncio.sleep(0.5)
611+
await asyncio.sleep(TimingConstants.SHORT_DELAY)
611612

612613
return {"message": "Log forwarding service started"}
613614
except Exception as e:

autobot-backend/api/long_running_operations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ async def migrate_existing_operation(
437437
async def migrated_operation(context):
438438
"""Placeholder for migrated operation"""
439439
await context.update_progress("Migration placeholder", 0, 1)
440-
await asyncio.sleep(1) # Simulate work
440+
await asyncio.sleep(TimingConstants.STANDARD_DELAY) # Simulate work
441441
await context.update_progress("Completed", 1, 1)
442442
return {"status": "migrated", "original_timeout": timeout_seconds}
443443

autobot-backend/api/monitoring.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848

4949
# Issue #474: Import ServiceURLs for AlertManager integration
5050
from constants.network_constants import ServiceURLs
51+
from constants.threshold_constants import TimingConstants
5152
from type_defs.common import Metadata
5253
from utils.performance_monitor import (
5354
add_alert_callback,
@@ -1137,7 +1138,7 @@ async def test_performance_monitoring(
11371138
):
11381139
"""Test endpoint to demonstrate performance monitoring. Issue #744: Requires admin authentication."""
11391140
# Simulate some work
1140-
await asyncio.sleep(0.1)
1141+
await asyncio.sleep(TimingConstants.MICRO_DELAY)
11411142

11421143
# Collect current metrics
11431144
metrics = await collect_metrics()

autobot-backend/api/process_management.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from pydantic import BaseModel, Field
1818

1919
from auth_middleware import get_current_user
20+
from constants.threshold_constants import TimingConstants
2021
from services.process_adapter_service import ProcessAdapterService
2122

2223
logger = logging.getLogger(__name__)
@@ -201,7 +202,7 @@ async def stream_process_logs(
201202
):
202203
await websocket.send_json({"done": True, "status": data["status"]})
203204
break
204-
await asyncio.sleep(0.5)
205+
await asyncio.sleep(TimingConstants.SHORT_DELAY)
205206
except Exception:
206207
pass
207208
finally:

autobot-backend/api/terminal_websocket.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from starlette.websockets import WebSocketState
1414

1515
from agents.system_command_agent import SystemCommandAgent
16+
from constants.threshold_constants import TimingConstants
1617
from event_manager import event_manager
1718
from services.terminal_completion_service import TerminalCompletionService
1819
from services.terminal_history_service import TerminalHistoryService
@@ -399,7 +400,7 @@ async def _subscribe_to_terminal_events(self, chat_id: str, websocket: WebSocket
399400
# Keep the subscription alive
400401
try:
401402
while chat_id in self.active_connections:
402-
await asyncio.sleep(1)
403+
await asyncio.sleep(TimingConstants.STANDARD_DELAY)
403404
finally:
404405
# Unsubscribe all handlers
405406
for event_type, handler in handlers.items():

autobot-backend/api/vnc_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ async def vnc_mouse_drag(
532532
for x, y in path_points[1:]: # Skip first point (already there)
533533
_run_xdotool_cmd(["mousemove", str(x), str(y)])
534534
# Small delay between movements for smooth curve
535-
await asyncio.sleep(0.01)
535+
await asyncio.sleep(TimingConstants.POLL_INTERVAL)
536536

537537
# Release mouse button at end position
538538
return _run_xdotool_cmd(["mouseup", "1"])

autobot-backend/constants/threshold_constants.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,15 @@ class KnowledgeSyncConfig:
112112
class TimingConstants:
113113
"""Common timing values used throughout the codebase."""
114114

115+
# Sub-millisecond yields (asyncio.sleep)
116+
YIELD_INTERVAL = 0.001 # Brief yield to event loop between batches
117+
115118
# Short delays (sub-second)
116119
POLL_INTERVAL = 0.01 # Short polling loop delay to prevent CPU spinning
120+
FAST_POLL_INTERVAL = 0.02 # Fast polling / short scan simulation delay
117121
STREAMING_CHUNK_DELAY = 0.05 # Delay between streaming chunks for UX
118122
MICRO_DELAY = 0.1
123+
DEBOUNCE_INTERVAL_S = 0.2 # Debounce / short API simulation delay
119124
SHORT_DELAY = 0.5
120125
STANDARD_DELAY = 1.0
121126

@@ -130,6 +135,7 @@ class TimingConstants:
130135
VERY_LONG_TIMEOUT = 300
131136

132137
# Long interval values
138+
SESSION_CLEANUP_INTERVAL = 60 # Background session cleanup polling interval (1 min)
133139
HOURLY_INTERVAL = 3600 # 1 hour in seconds
134140

135141
# Error recovery

0 commit comments

Comments
 (0)