Skip to content

Commit 2b99dd8

Browse files
committed
Refactor long operation handling in agent and file update processes
- Updated documentation to replace references to "Async Celery worker" with "Background queue" for long operations in `auto_select_agent.py`, `execute_specific_agent.py`, and `update_file.py`. - Enhanced the `MaterializeResponse` model to include an operation ID for better tracking of materialization jobs. - Improved SSE client handling by introducing context managers for better resource management during streaming operations. - Adjusted timeout settings for SSE streaming in `subgraph_workspace_client.py` to accommodate longer-running jobs. These changes improve clarity in operation handling and enhance the robustness of the streaming and materialization processes.
1 parent bf96a16 commit 2b99dd8

7 files changed

Lines changed: 128 additions & 115 deletions

File tree

‎robosystems_client/api/agent/auto_select_agent.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def sync_detailed(
134134
**Execution Strategies (automatic):**
135135
- Fast operations (<5s): Immediate synchronous response
136136
- Medium operations (5-30s): SSE streaming with progress updates
137-
- Long operations (>30s): Async Celery worker with operation tracking
137+
- Long operations (>30s): Background queue with operation tracking
138138
139139
**Response Mode Override:**
140140
Use query parameter `?mode=sync|async` to override automatic strategy selection.
@@ -228,7 +228,7 @@ def sync(
228228
**Execution Strategies (automatic):**
229229
- Fast operations (<5s): Immediate synchronous response
230230
- Medium operations (5-30s): SSE streaming with progress updates
231-
- Long operations (>30s): Async Celery worker with operation tracking
231+
- Long operations (>30s): Background queue with operation tracking
232232
233233
**Response Mode Override:**
234234
Use query parameter `?mode=sync|async` to override automatic strategy selection.
@@ -317,7 +317,7 @@ async def asyncio_detailed(
317317
**Execution Strategies (automatic):**
318318
- Fast operations (<5s): Immediate synchronous response
319319
- Medium operations (5-30s): SSE streaming with progress updates
320-
- Long operations (>30s): Async Celery worker with operation tracking
320+
- Long operations (>30s): Background queue with operation tracking
321321
322322
**Response Mode Override:**
323323
Use query parameter `?mode=sync|async` to override automatic strategy selection.
@@ -409,7 +409,7 @@ async def asyncio(
409409
**Execution Strategies (automatic):**
410410
- Fast operations (<5s): Immediate synchronous response
411411
- Medium operations (5-30s): SSE streaming with progress updates
412-
- Long operations (>30s): Async Celery worker with operation tracking
412+
- Long operations (>30s): Background queue with operation tracking
413413
414414
**Response Mode Override:**
415415
Use query parameter `?mode=sync|async` to override automatic strategy selection.

‎robosystems_client/api/agent/execute_specific_agent.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def sync_detailed(
124124
**Execution Strategies (automatic):**
125125
- Fast operations (<5s): Immediate synchronous response
126126
- Medium operations (5-30s): SSE streaming with progress updates
127-
- Long operations (>30s): Async Celery worker with operation tracking
127+
- Long operations (>30s): Background queue with operation tracking
128128
129129
**Response Mode Override:**
130130
Use query parameter `?mode=sync|async` to override automatic strategy selection.
@@ -179,7 +179,7 @@ def sync(
179179
**Execution Strategies (automatic):**
180180
- Fast operations (<5s): Immediate synchronous response
181181
- Medium operations (5-30s): SSE streaming with progress updates
182-
- Long operations (>30s): Async Celery worker with operation tracking
182+
- Long operations (>30s): Background queue with operation tracking
183183
184184
**Response Mode Override:**
185185
Use query parameter `?mode=sync|async` to override automatic strategy selection.
@@ -229,7 +229,7 @@ async def asyncio_detailed(
229229
**Execution Strategies (automatic):**
230230
- Fast operations (<5s): Immediate synchronous response
231231
- Medium operations (5-30s): SSE streaming with progress updates
232-
- Long operations (>30s): Async Celery worker with operation tracking
232+
- Long operations (>30s): Background queue with operation tracking
233233
234234
**Response Mode Override:**
235235
Use query parameter `?mode=sync|async` to override automatic strategy selection.
@@ -282,7 +282,7 @@ async def asyncio(
282282
**Execution Strategies (automatic):**
283283
- Fast operations (<5s): Immediate synchronous response
284284
- Medium operations (5-30s): SSE streaming with progress updates
285-
- Long operations (>30s): Async Celery worker with operation tracking
285+
- Long operations (>30s): Background queue with operation tracking
286286
287287
**Response Mode Override:**
288288
Use query parameter `?mode=sync|async` to override automatic strategy selection.

‎robosystems_client/api/files/update_file.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def sync_detailed(
103103
**What Happens (status='uploaded'):**
104104
1. File validated in S3
105105
2. Row count calculated
106-
3. DuckDB staging triggered immediately (Celery task)
106+
3. DuckDB staging triggered immediately (background task)
107107
4. If ingest_to_graph=true, graph ingestion queued
108108
5. File queryable in DuckDB within seconds
109109
@@ -165,7 +165,7 @@ def sync(
165165
**What Happens (status='uploaded'):**
166166
1. File validated in S3
167167
2. Row count calculated
168-
3. DuckDB staging triggered immediately (Celery task)
168+
3. DuckDB staging triggered immediately (background task)
169169
4. If ingest_to_graph=true, graph ingestion queued
170170
5. File queryable in DuckDB within seconds
171171
@@ -222,7 +222,7 @@ async def asyncio_detailed(
222222
**What Happens (status='uploaded'):**
223223
1. File validated in S3
224224
2. Row count calculated
225-
3. DuckDB staging triggered immediately (Celery task)
225+
3. DuckDB staging triggered immediately (background task)
226226
4. If ingest_to_graph=true, graph ingestion queued
227227
5. File queryable in DuckDB within seconds
228228
@@ -282,7 +282,7 @@ async def asyncio(
282282
**What Happens (status='uploaded'):**
283283
1. File validated in S3
284284
2. Row count calculated
285-
3. DuckDB staging triggered immediately (Celery task)
285+
3. DuckDB staging triggered immediately (background task)
286286
4. If ingest_to_graph=true, graph ingestion queued
287287
5. File queryable in DuckDB within seconds
288288

‎robosystems_client/extensions/materialization_client.py‎

Lines changed: 73 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
sync_detailed as get_materialization_status,
1616
)
1717
from ..models.materialize_request import MaterializeRequest
18+
from .operation_client import OperationClient, OperationProgress, MonitorOptions
1819

1920
logger = logging.getLogger(__name__)
2021

@@ -27,6 +28,7 @@ class MaterializationOptions:
2728
rebuild: bool = False
2829
force: bool = False
2930
on_progress: Optional[Callable[[str], None]] = None
31+
timeout: Optional[int] = 600 # 10 minute default timeout
3032

3133

3234
@dataclass
@@ -66,6 +68,14 @@ def __init__(self, config: Dict[str, Any]):
6668
self.base_url = config["base_url"]
6769
self.headers = config.get("headers", {})
6870
self.token = config.get("token")
71+
self._operation_client = None
72+
73+
@property
74+
def operation_client(self) -> OperationClient:
75+
"""Get or create the operation client for SSE monitoring."""
76+
if self._operation_client is None:
77+
self._operation_client = OperationClient(self.config)
78+
return self._operation_client
6979

7080
def materialize(
7181
self,
@@ -75,13 +85,13 @@ def materialize(
7585
"""
7686
Materialize graph from DuckDB staging tables.
7787
78-
Rebuilds the complete graph database from the current state of DuckDB
79-
staging tables. Automatically discovers all tables, materializes them in
80-
the correct order (nodes before relationships), and clears the staleness flag.
88+
Submits a materialization job to Dagster and monitors progress via SSE.
89+
The operation runs asynchronously on the server but this method waits
90+
for completion and returns the final result.
8191
8292
Args:
8393
graph_id: Graph database identifier
84-
options: Materialization options (ignore_errors, rebuild, force)
94+
options: Materialization options (ignore_errors, rebuild, force, timeout)
8595
8696
Returns:
8797
MaterializationResult with detailed execution information
@@ -96,7 +106,7 @@ def materialize(
96106

97107
try:
98108
if options.on_progress:
99-
options.on_progress("Starting graph materialization...")
109+
options.on_progress("Submitting materialization job...")
100110

101111
request = MaterializeRequest(
102112
ignore_errors=options.ignore_errors,
@@ -125,6 +135,7 @@ def materialize(
125135

126136
response = materialize_graph(**kwargs)
127137

138+
# Handle non-200 status codes
128139
if response.status_code != 200 or not response.parsed:
129140
error_msg = f"Materialization failed: {response.status_code}"
130141
if hasattr(response, "content"):
@@ -148,25 +159,68 @@ def materialize(
148159
error=error_msg,
149160
)
150161

162+
# Get the operation_id from the queued response
151163
result_data = response.parsed
164+
operation_id = result_data.operation_id
152165

153166
if options.on_progress:
154-
options.on_progress(
155-
f"✅ Materialization complete: {len(result_data.tables_materialized)} tables, "
156-
f"{result_data.total_rows:,} rows in {result_data.execution_time_ms:.2f}ms"
157-
)
158-
159-
return MaterializationResult(
160-
status=result_data.status,
161-
was_stale=result_data.was_stale,
162-
stale_reason=result_data.stale_reason,
163-
tables_materialized=result_data.tables_materialized,
164-
total_rows=result_data.total_rows,
165-
execution_time_ms=result_data.execution_time_ms,
166-
message=result_data.message,
167-
success=True,
167+
options.on_progress(f"Materialization queued (operation: {operation_id})")
168+
169+
# Monitor the operation via SSE until completion
170+
def on_sse_progress(progress: OperationProgress):
171+
if options.on_progress:
172+
msg = progress.message
173+
if progress.percentage is not None:
174+
msg += f" ({progress.percentage:.0f}%)"
175+
options.on_progress(msg)
176+
177+
monitor_options = MonitorOptions(
178+
on_progress=on_sse_progress,
179+
timeout=options.timeout,
168180
)
169181

182+
op_result = self.operation_client.monitor_operation(operation_id, monitor_options)
183+
184+
# Convert operation result to materialization result
185+
if op_result.status.value == "completed":
186+
# Extract details from SSE completion event result
187+
sse_result = op_result.result or {}
188+
189+
if options.on_progress:
190+
tables = sse_result.get("tables_materialized", [])
191+
rows = sse_result.get("total_rows", 0)
192+
time_ms = sse_result.get("execution_time_ms", 0)
193+
options.on_progress(
194+
f"✅ Materialization complete: {len(tables)} tables, "
195+
f"{rows:,} rows in {time_ms:.2f}ms"
196+
)
197+
198+
return MaterializationResult(
199+
status="success",
200+
was_stale=sse_result.get("was_stale", False),
201+
stale_reason=sse_result.get("stale_reason"),
202+
tables_materialized=sse_result.get("tables_materialized", []),
203+
total_rows=sse_result.get("total_rows", 0),
204+
execution_time_ms=sse_result.get(
205+
"execution_time_ms", op_result.execution_time_ms or 0
206+
),
207+
message=sse_result.get("message", "Graph materialized successfully"),
208+
success=True,
209+
)
210+
else:
211+
# Operation failed or was cancelled
212+
return MaterializationResult(
213+
status=op_result.status.value,
214+
was_stale=False,
215+
stale_reason=None,
216+
tables_materialized=[],
217+
total_rows=0,
218+
execution_time_ms=op_result.execution_time_ms or 0,
219+
message=op_result.error or f"Operation {op_result.status.value}",
220+
success=False,
221+
error=op_result.error,
222+
)
223+
170224
except Exception as e:
171225
logger.error(f"Materialization failed: {e}")
172226
return MaterializationResult(

‎robosystems_client/extensions/sse_client.py‎

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,10 @@ def connect(self, operation_id: str, from_sequence: int = 0) -> None:
104104

105105
try:
106106
self.client = httpx.Client(timeout=self.config.timeout)
107-
self._response = self.client.stream("GET", url, params=params, headers=headers)
108-
self._response.__enter__()
107+
self._context_manager = self.client.stream(
108+
"GET", url, params=params, headers=headers
109+
)
110+
self._response = self._context_manager.__enter__()
109111

110112
self.reconnect_attempts = 0
111113
self.emit("connected", None)
@@ -124,19 +126,16 @@ def _process_events(self) -> None:
124126

125127
try:
126128
event_buffer = {"event": None, "data": [], "id": None, "retry": None}
127-
print("[SSE DEBUG] Starting to process events...")
128129

129130
for line in self._response.iter_lines():
130131
if self.closed:
131-
print("[SSE DEBUG] Stream closed, breaking out of loop")
132132
break
133133

134134
line = line.strip()
135135

136136
# Empty line indicates end of event
137137
if not line:
138138
if event_buffer["data"] or event_buffer["event"]:
139-
print(f"[SSE DEBUG] Dispatching event: {event_buffer.get('event')}")
140139
self._dispatch_event(event_buffer)
141140
event_buffer = {"event": None, "data": [], "id": None, "retry": None}
142141
continue
@@ -172,13 +171,9 @@ def _process_events(self) -> None:
172171

173172
# Handle final event if stream ends without empty line
174173
if event_buffer["data"] or event_buffer["event"]:
175-
print("[SSE DEBUG] Dispatching final event after stream end")
176174
self._dispatch_event(event_buffer)
177175

178-
print("[SSE DEBUG] Event processing loop ended")
179-
180176
except Exception as error:
181-
print(f"[SSE DEBUG] Exception in event processing: {error}")
182177
if not self.closed:
183178
self.emit("error", error)
184179

@@ -214,13 +209,14 @@ def _dispatch_event(self, event_buffer: Dict[str, Any]) -> None:
214209
# Emit typed event
215210
self.emit(event_type, parsed_data)
216211

217-
# Check for completion events
212+
# Check for completion events - just set flag, don't close from within loop
213+
# The loop will break on next iteration and close() will be called in finally
218214
if event_type in [
219215
EventType.OPERATION_COMPLETED.value,
220216
EventType.OPERATION_ERROR.value,
221217
EventType.OPERATION_CANCELLED.value,
222218
]:
223-
self.close()
219+
self.closed = True
224220

225221
def _handle_error(
226222
self, error: Exception, operation_id: str, from_sequence: int
@@ -285,12 +281,13 @@ def close(self):
285281
"""Close the SSE connection"""
286282
self.closed = True
287283

288-
if self._response:
284+
if hasattr(self, "_context_manager") and self._context_manager:
289285
try:
290-
self._response.__exit__(None, None, None)
286+
self._context_manager.__exit__(None, None, None)
291287
except Exception:
292288
pass
293-
self._response = None
289+
self._context_manager = None
290+
self._response = None
294291

295292
if self.client:
296293
self.client.close()
@@ -334,10 +331,10 @@ async def connect(self, operation_id: str, from_sequence: int = 0) -> None:
334331

335332
try:
336333
self.client = httpx.AsyncClient(timeout=self.config.timeout)
337-
self._response = await self.client.stream(
334+
self._context_manager = self.client.stream(
338335
"GET", url, params=params, headers=headers
339336
)
340-
await self._response.__aenter__()
337+
self._response = await self._context_manager.__aenter__()
341338

342339
self.reconnect_attempts = 0
343340
self.emit("connected", None)
@@ -401,13 +398,9 @@ async def _process_events(self) -> None:
401398

402399
# Handle final event if stream ends without empty line
403400
if event_buffer["data"] or event_buffer["event"]:
404-
print("[SSE DEBUG] Dispatching final event after stream end")
405401
self._dispatch_event(event_buffer)
406402

407-
print("[SSE DEBUG] Event processing loop ended")
408-
409403
except Exception as error:
410-
print(f"[SSE DEBUG] Exception in event processing: {error}")
411404
if not self.closed:
412405
self.emit("error", error)
413406

@@ -443,13 +436,14 @@ def _dispatch_event(self, event_buffer: Dict[str, Any]):
443436
# Emit typed event
444437
self.emit(event_type, parsed_data)
445438

446-
# Check for completion events
439+
# Check for completion events - just set flag, don't close from within loop
440+
# The loop will break on next iteration and close() will be called in finally
447441
if event_type in [
448442
EventType.OPERATION_COMPLETED.value,
449443
EventType.OPERATION_ERROR.value,
450444
EventType.OPERATION_CANCELLED.value,
451445
]:
452-
asyncio.create_task(self.close())
446+
self.closed = True
453447

454448
async def _handle_error(
455449
self, error: Exception, operation_id: str, from_sequence: int
@@ -512,12 +506,13 @@ async def close(self):
512506
"""Close the SSE connection (async)"""
513507
self.closed = True
514508

515-
if self._response:
509+
if hasattr(self, "_context_manager") and self._context_manager:
516510
try:
517-
await self._response.__aexit__(None, None, None)
511+
await self._context_manager.__aexit__(None, None, None)
518512
except Exception:
519513
pass
520-
self._response = None
514+
self._context_manager = None
515+
self._response = None
521516

522517
if self.client:
523518
await self.client.aclose()

0 commit comments

Comments
 (0)