web3-systemic-agent 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
src/task_worker.py ADDED
@@ -0,0 +1,325 @@
1
+ """
2
+ Asynchronous Worker Pool and Job Store for Web3 Condition-Action Trigger Agent.
3
+ Manages background job queues, decoupled execution workers, and state transitions.
4
+ """
5
+
6
+ import asyncio
7
+ from datetime import datetime, timezone
8
+ from enum import Enum
9
+ import logging
10
+ import os
11
+ import sys
12
+ import time
13
+ import traceback
14
+ from typing import Dict, Any, Optional, List
15
+ import uuid
16
+ from pydantic import BaseModel, Field
17
+
18
+ # Ensure module search paths support running directly or as a package
19
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
20
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
21
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
22
+ for _p in (_ROOT_DIR, _SRC_DIR):
23
+ if _p not in sys.path:
24
+ sys.path.insert(0, _p)
25
+
26
+ try:
27
+ from src.schemas import ConditionRulePayload, FinalAgentResponse
28
+ from src.engine import ConditionAgentEngine
29
+ from src.storage import AgentStorage
30
+ except ImportError:
31
+ from schemas import ConditionRulePayload, FinalAgentResponse
32
+ from engine import ConditionAgentEngine
33
+ from storage import AgentStorage
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ DEFAULT_JOB_TTL_SECONDS = 3600
38
+ DEFAULT_MAX_JOBS = 10000
39
+
40
+
41
+ class JobStatus(str, Enum):
42
+ QUEUED = "QUEUED"
43
+ PROCESSING = "PROCESSING"
44
+ COMPLETED = "COMPLETED"
45
+ FAILED = "FAILED"
46
+ CANCELLED = "CANCELLED"
47
+
48
+
49
+ class JobRecord(BaseModel):
50
+ job_id: str
51
+ status: JobStatus = JobStatus.QUEUED
52
+ payload: ConditionRulePayload
53
+ result: Optional[FinalAgentResponse] = None
54
+ error: Optional[str] = None
55
+ created_at: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
56
+ updated_at: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
57
+
58
+
59
+ class JobStore:
60
+ """
61
+ In-memory storage and lifecycle management for asynchronous evaluation jobs.
62
+ Implements TTL expiration cleanup and bounded capacity eviction.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ ttl_seconds: Optional[float] = None,
68
+ max_jobs: Optional[int] = None,
69
+ ):
70
+ self.ttl_seconds = float(
71
+ ttl_seconds
72
+ if ttl_seconds is not None
73
+ else os.getenv("JOB_TTL_SECONDS", DEFAULT_JOB_TTL_SECONDS)
74
+ )
75
+ self.max_jobs = int(
76
+ max_jobs
77
+ if max_jobs is not None
78
+ else os.getenv("JOB_MAX_COUNT", DEFAULT_MAX_JOBS)
79
+ )
80
+ self._jobs: Dict[str, JobRecord] = {}
81
+ self._job_created_at: Dict[str, float] = {}
82
+ self._job_updated_at: Dict[str, float] = {}
83
+
84
+ def cleanup_expired(self, now: Optional[float] = None) -> int:
85
+ """
86
+ Removes terminal jobs (COMPLETED, FAILED, CANCELLED) older than ttl_seconds.
87
+ """
88
+ current_time = now if now is not None else time.time()
89
+ terminal_states = {JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.CANCELLED}
90
+ expired_ids = []
91
+
92
+ for jid, job in list(self._jobs.items()):
93
+ if job.status in terminal_states:
94
+ last_time = self._job_updated_at.get(jid, self._job_created_at.get(jid, current_time))
95
+ if (current_time - last_time) > self.ttl_seconds:
96
+ expired_ids.append(jid)
97
+
98
+ for jid in expired_ids:
99
+ self._jobs.pop(jid, None)
100
+ self._job_created_at.pop(jid, None)
101
+ self._job_updated_at.pop(jid, None)
102
+
103
+ return len(expired_ids)
104
+
105
+ def create_job(
106
+ self, payload: ConditionRulePayload, job_id: Optional[str] = None
107
+ ) -> JobRecord:
108
+ self.cleanup_expired()
109
+
110
+ # Enforce bounded capacity
111
+ while len(self._jobs) >= self.max_jobs:
112
+ terminal_states = {JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.CANCELLED}
113
+ terminal_jids = [
114
+ jid for jid, j in self._jobs.items() if j.status in terminal_states
115
+ ]
116
+ if terminal_jids:
117
+ # Evict oldest terminal job
118
+ oldest_term_jid = min(
119
+ terminal_jids, key=lambda j: self._job_created_at.get(j, 0.0)
120
+ )
121
+ self._jobs.pop(oldest_term_jid, None)
122
+ self._job_created_at.pop(oldest_term_jid, None)
123
+ self._job_updated_at.pop(oldest_term_jid, None)
124
+ else:
125
+ # Evict oldest job overall (FIFO)
126
+ oldest_jid = min(
127
+ self._jobs.keys(), key=lambda j: self._job_created_at.get(j, 0.0)
128
+ )
129
+ self._jobs.pop(oldest_jid, None)
130
+ self._job_created_at.pop(oldest_jid, None)
131
+ self._job_updated_at.pop(oldest_jid, None)
132
+
133
+ jid = job_id or str(uuid.uuid4())
134
+ now_dt = datetime.now(timezone.utc).isoformat()
135
+ now_ts = time.time()
136
+
137
+ job = JobRecord(
138
+ job_id=jid,
139
+ status=JobStatus.QUEUED,
140
+ payload=payload,
141
+ result=None,
142
+ error=None,
143
+ created_at=now_dt,
144
+ updated_at=now_dt,
145
+ )
146
+ self._jobs[jid] = job
147
+ self._job_created_at[jid] = now_ts
148
+ self._job_updated_at[jid] = now_ts
149
+ return job
150
+
151
+ def get_job(self, job_id: str) -> Optional[JobRecord]:
152
+ self.cleanup_expired()
153
+ return self._jobs.get(job_id)
154
+
155
+ def update_job(
156
+ self,
157
+ job_id: str,
158
+ status: Optional[JobStatus] = None,
159
+ result: Optional[FinalAgentResponse] = None,
160
+ error: Optional[str] = None,
161
+ ) -> Optional[JobRecord]:
162
+ job = self._jobs.get(job_id)
163
+ if not job:
164
+ return None
165
+ now_dt = datetime.now(timezone.utc).isoformat()
166
+ now_ts = time.time()
167
+ if status is not None:
168
+ job.status = status
169
+ if result is not None:
170
+ job.result = result
171
+ if error is not None:
172
+ job.error = error
173
+ job.updated_at = now_dt
174
+ self._job_updated_at[job_id] = now_ts
175
+ return job
176
+
177
+ def cancel_job(self, job_id: str) -> bool:
178
+ job = self._jobs.get(job_id)
179
+ if not job:
180
+ return False
181
+ job.status = JobStatus.CANCELLED
182
+ now_dt = datetime.now(timezone.utc).isoformat()
183
+ now_ts = time.time()
184
+ job.updated_at = now_dt
185
+ self._job_updated_at[job_id] = now_ts
186
+ return True
187
+
188
+
189
+ class AgentWorkerPool:
190
+ """
191
+ Asynchronous queue worker pool executing ConditionAgentEngine jobs concurrently.
192
+ """
193
+
194
+ def __init__(
195
+ self,
196
+ engine: Optional[ConditionAgentEngine] = None,
197
+ num_workers: int = 2,
198
+ job_store: Optional[JobStore] = None,
199
+ storage: Optional[Any] = None,
200
+ ttl_seconds: Optional[float] = None,
201
+ max_jobs: Optional[int] = None,
202
+ ):
203
+ self.engine = engine if engine is not None else ConditionAgentEngine()
204
+ self.num_workers = num_workers
205
+ self.storage = storage
206
+ self.job_store = (
207
+ job_store
208
+ if job_store is not None
209
+ else JobStore(ttl_seconds=ttl_seconds, max_jobs=max_jobs)
210
+ )
211
+ self.queue: asyncio.Queue[str] = asyncio.Queue()
212
+ self._worker_tasks: List[asyncio.Task] = []
213
+ self._started = False
214
+ self._running = False
215
+
216
+ def start(self) -> None:
217
+ """
218
+ Starts the background worker tasks if not already running.
219
+ """
220
+ if self._started:
221
+ return
222
+ self._started = True
223
+ self._running = True
224
+ for _ in range(self.num_workers):
225
+ task = asyncio.create_task(self._worker_loop())
226
+ self._worker_tasks.append(task)
227
+
228
+ def enqueue(self, payload: ConditionRulePayload) -> str:
229
+ """
230
+ Enqueues a new rule payload for asynchronous evaluation and returns its job_id.
231
+ Automatically starts the background workers if they are not yet running.
232
+ """
233
+ if not self._started:
234
+ self.start()
235
+ job = self.job_store.create_job(payload=payload)
236
+ self.queue.put_nowait(job.job_id)
237
+ return job.job_id
238
+
239
+ def get_job(self, job_id: str) -> Optional[JobRecord]:
240
+ """
241
+ Retrieves the current job record by job_id.
242
+ """
243
+ return self.job_store.get_job(job_id)
244
+
245
+ def cancel_job(self, job_id: str) -> bool:
246
+ """
247
+ Marks an enqueued or active job as CANCELLED.
248
+ """
249
+ return self.job_store.cancel_job(job_id)
250
+
251
+ async def shutdown(self) -> None:
252
+ """
253
+ Asynchronously stops workers and cleanly drains worker coroutines.
254
+ """
255
+ self._running = False
256
+ for task in self._worker_tasks:
257
+ task.cancel()
258
+ if self._worker_tasks:
259
+ await asyncio.gather(*self._worker_tasks, return_exceptions=True)
260
+ self._worker_tasks.clear()
261
+ self._started = False
262
+
263
+ def stop(self) -> None:
264
+ """
265
+ Synchronously cancels background worker tasks.
266
+ """
267
+ self._running = False
268
+ for task in self._worker_tasks:
269
+ task.cancel()
270
+ self._worker_tasks.clear()
271
+ self._started = False
272
+
273
+ async def _worker_loop(self) -> None:
274
+ while self._running:
275
+ try:
276
+ job_id = await self.queue.get()
277
+ except asyncio.CancelledError:
278
+ break
279
+ except Exception:
280
+ continue
281
+
282
+ try:
283
+ job = self.job_store.get_job(job_id)
284
+ if not job:
285
+ continue
286
+
287
+ # If job was cancelled before execution started, skip processing
288
+ if job.status == JobStatus.CANCELLED:
289
+ continue
290
+
291
+ # Transition to PROCESSING
292
+ self.job_store.update_job(job_id, status=JobStatus.PROCESSING)
293
+
294
+ try:
295
+ result = await self.engine.process_rule(
296
+ job.payload, source="worker", job_id=job_id
297
+ )
298
+ # Check if cancelled while processing was running
299
+ current_job = self.job_store.get_job(job_id)
300
+ if current_job and current_job.status == JobStatus.CANCELLED:
301
+ pass
302
+ else:
303
+ self.job_store.update_job(
304
+ job_id, status=JobStatus.COMPLETED, result=result
305
+ )
306
+ except Exception as exc:
307
+ logger.exception(f"Exception during worker execution for job '{job_id}': {exc}")
308
+ self.job_store.update_job(
309
+ job_id, status=JobStatus.FAILED, error=str(exc)
310
+ )
311
+ active_storage = self.storage or getattr(self.engine, "storage", None)
312
+ if active_storage:
313
+ try:
314
+ await active_storage.log_error(
315
+ stage="worker",
316
+ error_type=type(exc).__name__,
317
+ message=str(exc),
318
+ rule_id=job.payload.rule_id,
319
+ job_id=job_id,
320
+ traceback_str=traceback.format_exc(),
321
+ )
322
+ except Exception:
323
+ pass
324
+ finally:
325
+ self.queue.task_done()