Skip to content

Commit 05cfe00

Browse files
authored
fix: facade calls that fail against the current server (#233)
## Summary Fixes facade calls that fail against the current server. They came out of a review of the hand-written `clients/` layer. The test suite missed them because it answered every call with a mocked 200. The worst one: since server v1.11.10 the operator endpoint answers `202` unless a sync wait is requested. The generated parser turns a 202 into `None`, so every `OperatorClient` run and `operator_query()` call raised "Unexpected response format". ## Changes **Fixes** - **Operator:** a `202` is read from the raw body and followed to completion, over the stream or by polling `/status`. `OperatorOptions.mode` is now sent as `?mode=`. An HTTP error raises with its status instead of "Unexpected response format". - **Cypher query:** a queued `202` raises `QueuedQueryError` or waits on the stream, as documented. One body classifier is now shared by the sync client, the async client and `AuthenticatedClients.execute_cypher_query`. That last method also read a dict as an object and always returned empty data. - **Write credentials:** writes now send a credential the way reads do. `rfs…` API keys go in `X-API-Key`, anything else (a JWT from `token_provider`) as `Authorization: Bearer`. Before, every write sent a JWT as `X-API-Key` and got a 401. The graph, file, table and document clients now honour `token_provider`. - **`get_graph_info`** always raised "Graph not found"; fixed. - **`TableClient.list`** always returned `[]`, because it read a `table_type` the server doesn't send. - **`monitor_operation`** hung on a cancelled operation; it now settles. A stream that ends with no terminal event raises. - **`cancel_operation`** always returned `False`. It now reads the server's `status: "cancelled"`. - **Progress** now reads the server's `progress_percent`. - **`AsyncRoboSystemsClients`:** the async query and operation methods were `pass` stubs. They are now implemented with the async generated calls. - **`create_report` / `regenerate_report`** crashed on every call, because the request model expects `date` objects and the facade passed strings. - **`FileClient`** no longer leaks `UNSET` into `FileInfo`. **Additions (parity with the TypeScript client)** - `OperatorRunError(message, status, writes, operation_id)`, raised when a run fails or is cancelled, so a caller can show what the run already wrote. It subclasses `Exception`, so existing handlers still catch it. - `create_report(periods=…)`. - `list_information_blocks(scenario_id=…)`. This adds a variable to its `.graphql` operation and regenerates it. - `dispose_schedule`: `memo` and `reason` are now optional, matching the server. **Docs:** corrected the retry docstring on handler-raised 429s, the `_call_op` and `GraphClient` docstrings, and removed the uncalled `_unwrap`. ## Compatibility Rides a client **minor**. The facades are stable tier, but every change is backward compatible: new optional parameters, a new exception that subclasses what was raised before, and a new `TableInfo.s3_location` field added last with a default. Behaviour an integrator may notice: - A credential that does not start with `rfs` now goes out as Bearer on writes. Every real API key starts with `rfs`. - `TableInfo.table_type` is always `None`, because the server has no such field. Release-note lines: - *Fixed `OperatorClient` and `operator_query()` failing on every run since server v1.11.10.* - *Fixed writes failing with a JWT `token_provider`; queued Cypher queries; `get_graph_info`; `TableClient.list`; `cancel_operation`; monitoring a cancelled operation; `create_report`.* - *Implemented the async query and operation clients.* - *Added `OperatorRunError`, `create_report(periods)` and `list_information_blocks(scenario_id)`.* ## Testing - **New `tests/test_facade_wire_shapes.py` (30 tests):** answers the facades with the server's real status codes and bodies through the real generated parsers. Against the previous HEAD, 25 of the 26 that can run there fail. The 4 monitor tests hang on the old code. - **Corrected tests that had encoded the old behaviour:** the cancel-response body, the Cypher dict body, and the SSE header key. - **`just test-all`:** 647 passed, 17 skipped. ruff, format and basedpyright are clean. ## Follow-ups (not in this PR) - `OperationClient.monitor_operation`'s sync `timeout` is still not enforced, because `connect()` blocks. - A `mode="stream"` operator call fails when the server streams its 200 directly. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
2 parents 81df9c7 + d192135 commit 05cfe00

21 files changed

Lines changed: 1554 additions & 621 deletions

‎robosystems_client/clients/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
OperatorQueryRequest,
2222
OperatorOptions,
2323
QueuedOperatorError,
24+
OperatorRunError,
2425
)
2526
from .operation_client import (
2627
OperationClient,
@@ -144,6 +145,7 @@
144145
"OperatorQueryRequest",
145146
"OperatorOptions",
146147
"QueuedOperatorError",
148+
"OperatorRunError",
147149
# Operation Client
148150
"OperationClient",
149151
"OperationStatus",

‎robosystems_client/clients/auth_integration.py‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,14 @@ def authenticated_client(self) -> AuthenticatedClient:
8282
def execute_cypher_query(
8383
self, graph_id: str, query: str, parameters: Dict[str, Any] = None
8484
):
85-
"""Execute Cypher query using authenticated SDK client"""
85+
"""Execute Cypher query using authenticated SDK client.
86+
87+
A query the API queues (202) is followed over its SSE stream to the
88+
result, as :meth:`QueryClient.execute_query` does.
89+
"""
8690
from ..api.query.execute_cypher import sync_detailed
8791
from ..models.cypher_statement_request import CypherStatementRequest
92+
from .query_client import QueryOptions, QueryResult, _interpret_response
8893

8994
request = CypherStatementRequest(query=query, parameters=parameters or {})
9095

@@ -95,15 +100,17 @@ def execute_cypher_query(
95100
body=request,
96101
)
97102

98-
if response.parsed:
99-
return {
100-
"data": getattr(response.parsed, "data", []),
101-
"columns": getattr(response.parsed, "columns", []),
102-
"row_count": getattr(response.parsed, "row_count", 0),
103-
"execution_time_ms": getattr(response.parsed, "execution_time_ms", 0),
104-
}
105-
else:
106-
raise Exception(f"Query failed: {response.status_code}")
103+
outcome = _interpret_response(response, graph_id)
104+
if not isinstance(outcome, QueryResult):
105+
outcome = self.query._wait_for_query_completion(
106+
outcome.operation_id, QueryOptions()
107+
)
108+
return {
109+
"data": outcome.data,
110+
"columns": outcome.columns,
111+
"row_count": outcome.row_count,
112+
"execution_time_ms": outcome.execution_time_ms,
113+
}
107114

108115

109116
class CookieAuthClients(RoboSystemsClients):

‎robosystems_client/clients/document_client.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from ..models.search_request import SearchRequest
3131
from ..models.search_response import SearchResponse
3232
from ..types import UNSET
33+
from .token_utils import current_token
3334

3435

3536
class DocumentClient:
@@ -43,11 +44,12 @@ def __init__(self, config: Dict[str, Any]):
4344
self.timeout = config.get("timeout", 60)
4445

4546
def _get_client(self) -> AuthenticatedClient:
46-
if not self.token:
47+
token = current_token(self.config, self.token)
48+
if not token:
4749
raise Exception("No API key provided. Set X-API-Key in headers.")
4850
return retrying_authenticated_client(
4951
base_url=self.base_url,
50-
token=self.token,
52+
token=token,
5153
headers=self.headers,
5254
config=self.config,
5355
)

‎robosystems_client/clients/facade.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ def __init__(self, config: RoboSystemsClientConfig = None):
161161
"max_retries": config.max_retries,
162162
"retry_delay": config.retry_delay,
163163
"timeout": config.timeout,
164+
"token_provider": config.token_provider,
164165
}
165166

166167
# Initialize async clients

‎robosystems_client/clients/file_client.py‎

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,17 @@
2929
from ..models.file_upload_request import FileUploadRequest
3030
from ..models.ingest_file_op import IngestFileOp
3131
from ..models.delete_file_op import DeleteFileOp
32+
from ..types import Unset
33+
from .token_utils import current_token
3234

3335
logger = logging.getLogger(__name__)
3436

3537

38+
def _unset_to_none(value: Any) -> Any:
39+
"""A generated-model field as a plain value: ``UNSET`` becomes ``None``."""
40+
return None if isinstance(value, Unset) else value
41+
42+
3643
@dataclass
3744
class FileUploadOptions:
3845
"""Options for file upload operations"""
@@ -139,12 +146,14 @@ def upload(
139146

140147
from .retry import retrying_authenticated_client
141148

142-
if not self.token:
149+
token = current_token(self.config, self.token)
150+
151+
if not token:
143152
raise Exception("No API key provided. Set X-API-Key in headers.")
144153

145154
client = retrying_authenticated_client(
146155
base_url=self.base_url,
147-
token=self.token,
156+
token=token,
148157
headers=self.headers,
149158
config=self.config,
150159
)
@@ -295,12 +304,14 @@ def list(
295304
try:
296305
from .retry import retrying_authenticated_client
297306

298-
if not self.token:
307+
token = current_token(self.config, self.token)
308+
309+
if not token:
299310
raise Exception("No API key provided. Set X-API-Key in headers.")
300311

301312
client = retrying_authenticated_client(
302313
base_url=self.base_url,
303-
token=self.token,
314+
token=token,
304315
headers=self.headers,
305316
config=self.config,
306317
)
@@ -330,11 +341,11 @@ def list(
330341
file_name=f.file_name,
331342
file_format=f.file_format,
332343
size_bytes=f.size_bytes or 0,
333-
row_count=f.row_count,
344+
row_count=_unset_to_none(f.row_count),
334345
upload_status=f.upload_status,
335-
table_name=getattr(f, "table_name", ""),
336-
created_at=f.created_at,
337-
uploaded_at=f.uploaded_at,
346+
table_name=_unset_to_none(getattr(f, "table_name", None)) or "",
347+
created_at=_unset_to_none(f.created_at),
348+
uploaded_at=_unset_to_none(f.uploaded_at),
338349
)
339350
for f in files
340351
]
@@ -357,12 +368,14 @@ def get(self, graph_id: str, file_id: str) -> Optional[FileInfo]:
357368
try:
358369
from .retry import retrying_authenticated_client
359370

360-
if not self.token:
371+
token = current_token(self.config, self.token)
372+
373+
if not token:
361374
raise Exception("No API key provided. Set X-API-Key in headers.")
362375

363376
client = retrying_authenticated_client(
364377
base_url=self.base_url,
365-
token=self.token,
378+
token=token,
366379
headers=self.headers,
367380
config=self.config,
368381
)
@@ -386,12 +399,12 @@ def get(self, graph_id: str, file_id: str) -> Optional[FileInfo]:
386399
file_name=file_data.file_name,
387400
file_format=file_data.file_format,
388401
size_bytes=file_data.size_bytes or 0,
389-
row_count=file_data.row_count,
402+
row_count=_unset_to_none(file_data.row_count),
390403
upload_status=file_data.upload_status,
391-
table_name=file_data.table_name or "",
392-
created_at=file_data.created_at,
393-
uploaded_at=file_data.uploaded_at,
394-
layers=getattr(file_data, "layers", None),
404+
table_name=_unset_to_none(file_data.table_name) or "",
405+
created_at=_unset_to_none(file_data.created_at),
406+
uploaded_at=_unset_to_none(file_data.uploaded_at),
407+
layers=_unset_to_none(getattr(file_data, "layers", None)),
395408
)
396409

397410
except Exception as e:
@@ -413,12 +426,14 @@ def delete(self, graph_id: str, file_id: str, cascade: bool = False) -> bool:
413426
try:
414427
from .retry import retrying_authenticated_client
415428

416-
if not self.token:
429+
token = current_token(self.config, self.token)
430+
431+
if not token:
417432
raise Exception("No API key provided. Set X-API-Key in headers.")
418433

419434
client = retrying_authenticated_client(
420435
base_url=self.base_url,
421-
token=self.token,
436+
token=token,
422437
headers=self.headers,
423438
config=self.config,
424439
)

‎robosystems_client/clients/graph_client.py‎

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
automatic operation monitoring. Supports both SSE (Server-Sent Events)
55
for real-time updates and polling fallback.
66
7-
Graph lifecycle operations (create-subgraph, delete-subgraph, create-backup,
8-
change-tier, materialize) all go through the operations surface at
7+
The lifecycle operations this client wraps (materialize, change-tier) go
8+
through the operations surface at
99
``POST /v1/graphs/{graph_id}/operations/{op_name}`` and return an
10-
``OperationEnvelope``.
10+
``OperationEnvelope``. Subgraph and backup operations live on the same
11+
surface but have no method here — call the generated ``api`` functions.
1112
1213
Backups are a download capability: there is no customer-facing restore.
1314
Graphs with an upstream rebuild from it — entity graphs re-materialize,
@@ -23,7 +24,9 @@
2324

2425
import httpx
2526

27+
from ..types import Unset
2628
from .operation_client import OperationClient, OperationProgress, MonitorOptions
29+
from .token_utils import apply_auth_header, current_token
2730

2831
logger = logging.getLogger(__name__)
2932

@@ -96,8 +99,8 @@ class MaterializationResult:
9699
class GraphClient:
97100
"""Client for graph management and lifecycle operations.
98101
99-
Covers graph creation, info retrieval, and all graph lifecycle
100-
operations (materialize, subgraphs, backups, tier changes).
102+
Covers graph creation and deletion, info retrieval, materialization
103+
and tier changes.
101104
"""
102105

103106
def __init__(self, config: Dict[str, Any]):
@@ -118,12 +121,14 @@ def _get_authenticated_client(self):
118121
"""Build an AuthenticatedClient for API calls."""
119122
from .retry import retrying_authenticated_client
120123

121-
if not self.token:
124+
token = current_token(self.config, self.token)
125+
126+
if not token:
122127
raise ValueError("No API key provided. Set X-API-Key in headers.")
123128

124129
return retrying_authenticated_client(
125130
base_url=self.base_url,
126-
token=self.token,
131+
token=token,
127132
headers=self.headers,
128133
config=self.config,
129134
)
@@ -250,18 +255,18 @@ def get_graph_info(self, graph_id: str) -> GraphInfo:
250255
client = self._get_authenticated_client()
251256
response = get_graphs(client=client)
252257

253-
if not response.parsed:
258+
if response.status_code != 200 or not response.parsed:
254259
raise RuntimeError(f"Failed to get graphs: {response.status_code}")
255260

261+
# Every generated model carries `additional_properties` (the fields the
262+
# schema does not name), so the declared `graphs` field is read first.
256263
data = response.parsed
257-
graphs = None
258-
259264
if isinstance(data, dict):
260265
graphs = data.get("graphs", [])
261-
elif hasattr(data, "additional_properties"):
262-
graphs = data.additional_properties.get("graphs", [])
263266
elif hasattr(data, "graphs"):
264267
graphs = data.graphs
268+
elif hasattr(data, "additional_properties"):
269+
graphs = data.additional_properties.get("graphs", [])
265270
else:
266271
raise RuntimeError("Unexpected response format from get_graphs")
267272

@@ -290,16 +295,19 @@ def get_graph_info(self, graph_id: str) -> GraphInfo:
290295
status=graph_data.get("status"),
291296
)
292297
else:
298+
299+
def field(name: str) -> Any:
300+
value = getattr(graph_data, name, None)
301+
return None if isinstance(value, Unset) else value
302+
293303
return GraphInfo(
294-
graph_id=getattr(graph_data, "graph_id", None)
295-
or getattr(graph_data, "id", graph_id),
296-
graph_name=getattr(graph_data, "graph_name", None)
297-
or getattr(graph_data, "name", ""),
298-
description=getattr(graph_data, "description", None),
299-
schema_extensions=getattr(graph_data, "schema_extensions", None),
300-
tags=getattr(graph_data, "tags", None),
301-
created_at=getattr(graph_data, "created_at", None),
302-
status=getattr(graph_data, "status", None),
304+
graph_id=field("graph_id") or field("id") or graph_id,
305+
graph_name=field("graph_name") or field("name") or "",
306+
description=field("description"),
307+
schema_extensions=field("schema_extensions"),
308+
tags=field("tags"),
309+
created_at=field("created_at"),
310+
status=field("status"),
303311
)
304312

305313
# ---------------------------------------------------------------------------
@@ -535,7 +543,10 @@ def _wait_with_sse(
535543
) -> str:
536544
"""Wait for operation completion using SSE stream."""
537545
stream_url = f"{self.base_url}/v1/operations/{operation_id}/stream"
538-
headers = {"X-API-Key": self.token, "Accept": "text/event-stream"}
546+
headers = {"Accept": "text/event-stream"}
547+
token = current_token(self.config, self.token)
548+
if token:
549+
apply_auth_header(headers, token)
539550

540551
with httpx.Client(timeout=httpx.Timeout(timeout + 5.0)) as http_client:
541552
with http_client.stream("GET", stream_url, headers=headers) as response:

0 commit comments

Comments
 (0)