Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(weave): add with_new_client context for concurrent ch queries #3168

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions weave/trace_server/clickhouse_trace_server_batched.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,8 @@ def _add_feedback_to_calls(
return

feedback_query_req = make_feedback_query_req(project_id, calls)
feedback = self.feedback_query(feedback_query_req)
with self.with_new_client():
feedback = self.feedback_query(feedback_query_req)
hydrate_calls_with_feedback(calls, feedback)

def _get_refs_to_resolve(
Expand Down Expand Up @@ -430,9 +431,10 @@ def _expand_call_refs(
if not refs_to_resolve:
continue

vals = self._refs_read_batch_within_project(
project_id, list(refs_to_resolve.values()), ref_cache
)
with self.with_new_client():
vals = self._refs_read_batch_within_project(
project_id, list(refs_to_resolve.values()), ref_cache
)
for ((i, col), ref), val in zip(refs_to_resolve.items(), vals):
if isinstance(val, dict) and "_ref" not in val:
val["_ref"] = ref.uri()
Expand Down Expand Up @@ -1503,6 +1505,7 @@ def completions_create(
# Private Methods
@property
def ch_client(self) -> CHClient:
"""Returns and creates (if necessary) the clickhouse client"""
if not hasattr(self._thread_local, "ch_client"):
self._thread_local.ch_client = self._mint_client()
return self._thread_local.ch_client
Expand All @@ -1520,6 +1523,26 @@ def _mint_client(self) -> CHClient:
client.database = self._database
return client

@contextmanager
def with_new_client(self) -> Iterator[None]:
"""Context manager to use a new client for operations.
Each call gets a fresh client with its own clickhouse session ID.

Usage:
```
with self.with_new_client():
self.feedback_query(req)
```
"""
client = self._mint_client()
original_client = self.ch_client
self._thread_local.ch_client = client
try:
yield
finally:
self._thread_local.ch_client = original_client
client.close()

# def __del__(self) -> None:
# self.ch_client.close()

Expand Down
Loading