"""Remote ClickHouse executor that proxies via ObsessionDB's workbench API. 1:1 port of ``packages/plugin-obsessiondb/src/query/remote-executor.ts``. Exposes the same surface as the local :class:`ClickHouseClient` so existing commands (``drift``, ``pull``, ``migrate``, ``query``) don't care whether they're hitting a local Docker or a managed ObsessionDB instance: - ``execute(sql)`` — fire-and-forget; raises on ``result.error``. - ``query(sql)`` — returns rows as ``list[dict]``. - ``query_json(sql)`` — returns the full :class:`ClickHouseJsonQueryResult` envelope. - ``submit(sql, query_id?)`` — async query (sends query_id as the top-level ``queryId`` field of the execute call). - ``query_status(query_id)`` — polls ``system.processes`` then ``system.query_log`` via this same proxy. - ``database`` — the org's default database (introspected from the first ``listSchemaObjects`` row when needed). The class deliberately does NOT subclass ClickHouseClient: it just implements the same method names so duck-typing works. That avoids having to fake a ``clickhouse_connect`` Client object. """ from __future__ import annotations from collections.abc import Callable, Sequence from typing import Any from pydantic import BaseModel, ConfigDict from chkit.clickhouse.client import ( ClickHouseColumnMeta, ClickHouseJsonQueryResult, QueryResult, QueryStatus, query_log_outcome, ) from chkit.clickhouse.control import ( STRICT_CONTROL_SETTINGS, remaining_control_seconds, run_control_request, ) from chkit.clickhouse.introspect import ( IntrospectedTable, SchemaObjectRef, list_schema_objects, list_table_details, ) from chkit.clickhouse.replicas import all_replicas, resolve_replica_fanout from chkit.core.jsnum import js_math_round from chkit_plugin_obsessiondb.credentials import Credentials from chkit_plugin_obsessiondb.workbench_api import ( WorkbenchExecuteResult, workbench_query_execute, ) def _coerce_wire_settings( settings: dict[str, Any] | None, ) -> dict[str, Any] | None: """TS remote-executor settings coercion: booleans become 1/0, non-scalar values are dropped, and an empty map omits the ``settings`` field.""" if settings is None: return None coerced: dict[str, Any] = {} for key, value in settings.items(): if value is None: continue if isinstance(value, bool): coerced[key] = 1 if value else 0 elif isinstance(value, (str, int, float)): coerced[key] = value return coerced or None def _row_to_dict(row: Any, column_names: Sequence[str]) -> dict[str, Any]: """Normalize ``data`` rows — TS returns lists for unnamed, dicts otherwise.""" if isinstance(row, dict): return dict(row) if isinstance(row, list): return { column_names[i] if i < len(column_names) else str(i): value for i, value in enumerate(row) } return {"value": row} def normalize_query_data( result: WorkbenchExecuteResult, ) -> list[dict[str, Any]]: """Convert workbench result rows into plain dict rows.""" column_names = [col.name for col in result.meta] return [_row_to_dict(row, column_names) for row in result.data] def normalize_query_json_result( result: WorkbenchExecuteResult, ) -> ClickHouseJsonQueryResult: """Wrap workbench result as :class:`ClickHouseJsonQueryResult`.""" return ClickHouseJsonQueryResult( data=normalize_query_data(result), meta=[ ClickHouseColumnMeta(name=col.name, type=col.type) for col in result.meta ], rows=result.rows, statistics=result.statistics, query_id=result.query_id, ) def _raise_if_error(result: WorkbenchExecuteResult) -> None: if result.error: raise RuntimeError(result.error) class RemoteClickHouseClient: """Drop-in replacement for :class:`chkit.clickhouse.client.ClickHouseClient`.""" __slots__ = ("_credentials", "_database", "_service_slug") query_control_cluster: str = "default" def __init__( self, *, credentials: Credentials, service_slug: str, database: str = "default", ) -> None: self._credentials: Credentials = credentials self._service_slug: str = service_slug self._database: str = database # ---- context manager parity ---- def __enter__(self) -> RemoteClickHouseClient: return self def __exit__(self, *_exc: object) -> None: self.close() def close(self) -> None: # httpx clients are short-lived per-call; nothing to release. return @property def database(self) -> str: return self._database # ---- ClickHouseClient surface ---- def execute_tracked( self, statement: str, check: Callable[[], None], before_attempt: Callable[[], str], settings: dict[str, Any] | None = None, ) -> None: check() query_id = before_attempt() check() wire_settings = _coerce_wire_settings(settings) or {} wire_settings.pop("query_id", None) result = workbench_query_execute( self._credentials, service_slug=self._service_slug, query=statement, query_id=query_id, settings=wire_settings or None, ) _raise_if_error(result) def query_control( self, statement: str, timeout_ms: float, *, query_id: str | None = None, settings: dict[str, Any] | None = None, ) -> QueryResult: def request(deadline: float) -> QueryResult: result = workbench_query_execute( self._credentials, service_slug=self._service_slug, query=statement, timeout=remaining_control_seconds(deadline), query_id=query_id, settings=_coerce_wire_settings({ **{key: value for key, value in (settings or {}).items() if key != "query_id"}, **STRICT_CONTROL_SETTINGS, }), ) _raise_if_error(result) if result.truncated: raise RuntimeError( "Cancellation control result was truncated; complete proof is required" ) return QueryResult( column_names=[col.name for col in result.meta], rows=normalize_query_data(result), ) # The shared deadline bounds connection setup, the entire response and # error enrichment, rather than only inactivity between socket reads. return run_control_request(request, timeout_ms) def execute(self, statement: str, settings: dict[str, Any] | None = None) -> None: result = workbench_query_execute( self._credentials, service_slug=self._service_slug, query=statement, settings=_coerce_wire_settings(settings), ) _raise_if_error(result) def query( self, statement: str, settings: dict[str, Any] | None = None ) -> QueryResult: effective_settings = _coerce_wire_settings(settings) result = workbench_query_execute( self._credentials, service_slug=self._service_slug, query=statement, settings=effective_settings, ) _raise_if_error(result) column_names = [col.name for col in result.meta] return QueryResult( column_names=column_names, rows=normalize_query_data(result), ) def query_json(self, statement: str) -> ClickHouseJsonQueryResult: result = workbench_query_execute( self._credentials, service_slug=self._service_slug, query=statement ) _raise_if_error(result) return normalize_query_json_result(result) def submit( self, statement: str, query_id: str | None = None, settings: dict[str, Any] | None = None, *, before_send: Callable[[], None] | None = None, ) -> str: # Never start a request after the caller gave up on it, and stop one # still connecting before its first bytes (#767), as the native driver # does. QUERY_TIMEOUT bounds the connect (10 s). if before_send is not None: before_send() # The API takes the id as a top-level field and ignores a query_id # setting, which would leave the query under a random id. result = workbench_query_execute( self._credentials, service_slug=self._service_slug, query=statement, settings=_coerce_wire_settings(settings), query_id=query_id, guard=before_send, ) _raise_if_error(result) return query_id or result.query_id or "submitted" def insert( self, table: str, values: list[dict[str, Any]], *, compressed: bool = False, ) -> None: """Insert dict rows into ``table`` via a synthesized ``INSERT … VALUES`` over workbench. Mirrors the TS ``RemoteClickHouseClient.insert``: builds the SQL client-side (workbench accepts a SQL string, not a typed insert call) and proxies via ``execute``. ``compressed`` is accepted for API parity but currently unused on the wire — workbench manages compression at the transport layer. """ _ = compressed if not values: return first = values[0] columns = list(first.keys()) rendered_rows = ", ".join( "(" + ", ".join(_render_sql_literal(row.get(col)) for col in columns) + ")" for row in values ) column_list = ", ".join(columns) self.execute( f"INSERT INTO {table} ({column_list}) VALUES {rendered_rows}" ) def list_schema_objects(self) -> list[SchemaObjectRef]: """List non-system schema objects via the standalone introspect helper.""" return list_schema_objects(self) def list_table_details( self, databases: list[str] ) -> list[IntrospectedTable]: """Fetch full table shape for ``databases`` via the standalone helper.""" return list_table_details(self, databases) def query_status( self, query_id: str, *, after_time: str | None = None, every_replica: bool = False, running_only: bool = False, include_before_start: bool = False, ) -> QueryStatus: """Mirror of :meth:`ClickHouseClient.query_status`, proxied via workbench.""" # after_time bounds the query's start, as in the native client. A # string compared with a DateTime column may carry neither fractional # seconds nor a zone (TYPE_MISMATCH), so an ISO 8601 bound such as # '2026-10-02T16:22:23.641Z' goes through parseDateTimeBestEffort. # event_date prunes query_log's partitions: the entry is logged no # earlier than the query started. A day of slack covers a session # time zone other than the server's; toDate32, as a Date before 1970 wraps around. after_filter = ( " AND query_start_time >= " f"parseDateTimeBestEffort({_quote_string(after_time)})" f" AND event_date >= toDate32(parseDateTimeBestEffort({_quote_string(after_time)})) - 1" if after_time else "" ) # The query runs on the replica that received it, so a multi-replica # service reads every replica (#246). A poll skips a replica it cannot # reach; with every_replica the read fails instead. fanout = resolve_replica_fanout(self) def source(table: str) -> str: return all_replicas(fanout, table) if fanout else table read_settings = ( f" SETTINGS skip_unavailable_shards = {0 if every_replica else 1}" ) # migrate bounds an attach by how long the running attempt has run. # The workbench API returns every cell as a string. running = self.query( f"SELECT elapsed FROM {source('system.processes')} " f"WHERE user = currentUser() AND query_id = '{query_id}' LIMIT 1" f"{read_settings}" ) if running.rows: return QueryStatus( status="running", elapsed_ms=_elapsed_ms(running.rows[0].get("elapsed")), ) if running_only: return QueryStatus(status="unknown") types = ( "'QueryFinish', 'ExceptionWhileProcessing', 'ExceptionBeforeStart'" if include_before_start else "'QueryFinish', 'ExceptionWhileProcessing'" ) # With ExceptionBeforeStart, every entry of the id is read: a rejected # duplicate delivery logs one early, which must not hide the # QueryFinish of the attempt that ran (#767). log = self.query( "SELECT type, written_rows, written_bytes, query_duration_ms, exception, " "exception_code, toString(serverUUID()) AS server, " "toString(event_time_microseconds) AS event_at " f"FROM {source('system.query_log')} " f"WHERE user = currentUser() AND query_id = '{query_id}'" f" AND type IN ({types})" f"{after_filter}" " ORDER BY event_time DESC" f"{'' if include_before_start else ' LIMIT 1'}" f"{read_settings}" ) return query_log_outcome(log.rows) def _render_sql_literal(value: Any) -> str: """Render a Python value as a ClickHouse SQL literal for INSERT VALUES. Mirrors the TS ``RemoteClickHouseClient.insert`` literal rendering: NULL for None, bare numbers, booleans as 1/0, single-quoted escaped strings for everything else. """ if value is None: return "NULL" if isinstance(value, bool): return "1" if value else "0" if isinstance(value, (int, float)): return str(value) text = str(value).replace("\\", "\\\\").replace("'", "\\'") return f"'{text}'" def _safe_int(value: Any) -> int | None: # noqa: PLR0911 if value is None: return None if isinstance(value, bool): return int(value) if isinstance(value, (int, float)): return int(value) if isinstance(value, str): try: return int(value) except ValueError: try: return int(float(value)) except ValueError: return None return None def _quote_string(value: str) -> str: escaped = value.replace("\\", "\\\\").replace("'", "\\'") return f"'{escaped}'" def _elapsed_ms(value: Any) -> int | None: try: return int(js_math_round(float(value) * 1000)) except (TypeError, ValueError): return None # ---- factory used by the get_context hook ---- class RemoteContextConfig(BaseModel): """Inputs the plugin's ``get_context`` hook resolves to build the executor.""" model_config = ConfigDict(frozen=True, extra="ignore") service_slug: str database: str = "default" def create_remote_executor( credentials: Credentials, *, service_slug: str, database: str = "default", ) -> RemoteClickHouseClient: return RemoteClickHouseClient( credentials=credentials, service_slug=service_slug, database=database, ) __all__ = [ "RemoteClickHouseClient", "RemoteContextConfig", "create_remote_executor", "normalize_query_data", "normalize_query_json_result", ]