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

perf: [LS-2561] Stream compress multipart runs #1316

Merged
merged 57 commits into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from 46 commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
a5efbb8
start of compression
angus-langchain Dec 10, 2024
c10a8ad
manually encode
angus-langchain Dec 10, 2024
d456776
set boundary
angus-langchain Dec 10, 2024
0359235
add zstandard
angus-langchain Dec 10, 2024
08bce98
set limits from config
angus-langchain Dec 10, 2024
800472a
add slots
angus-langchain Dec 10, 2024
d4e45e1
lint
angus-langchain Dec 10, 2024
46c8740
fix mypy
angus-langchain Dec 10, 2024
a5cba8d
implement correct timeouts
angus-langchain Dec 10, 2024
c32cb0c
stream instead of read data from buffer
angus-langchain Dec 10, 2024
2aafc20
fix client type
angus-langchain Dec 10, 2024
03e4e02
separate compressed buffer from tracing queue
angus-langchain Dec 10, 2024
c952536
clean up update multipart
angus-langchain Dec 10, 2024
c3fdd36
address comments
angus-langchain Dec 10, 2024
d6b186d
just write directly to compressor instead of streaming
angus-langchain Dec 10, 2024
f061c0b
set trcing queue to none
angus-langchain Dec 10, 2024
8a0a60e
send multipart req
angus-langchain Dec 10, 2024
b2113ba
remove flush
angus-langchain Dec 11, 2024
982429a
remove print
angus-langchain Dec 11, 2024
5b58940
set compression level
angus-langchain Dec 11, 2024
f2e5ed9
remove prints
angus-langchain Dec 11, 2024
e7dc6bc
pass buffer directly to request
angus-langchain Dec 11, 2024
3ab6b39
resolve conflict
angus-langchain Dec 11, 2024
fb8fa96
lint
angus-langchain Dec 11, 2024
9d0a4ec
my fixes
angus-langchain Dec 11, 2024
f3e7971
black reformatting
angus-langchain Dec 11, 2024
066b9b6
multithreaded compression
angus-langchain Dec 11, 2024
ec15660
add parallel works for sending multipart req
angus-langchain Dec 12, 2024
35e9843
reformatting
angus-langchain Dec 12, 2024
59b5f27
black reformat
angus-langchain Dec 12, 2024
ce44b25
mypy
angus-langchain Dec 12, 2024
181f839
increase payload size to 20mb
angus-langchain Dec 12, 2024
0120dce
use multipart
angus-langchain Dec 12, 2024
e2ada65
use threadpoolexecutor
angus-langchain Dec 12, 2024
25f4f19
fix thread garbage collection
angus-langchain Dec 12, 2024
5b0cca4
add flush method
angus-langchain Dec 12, 2024
f59f7be
return early
angus-langchain Dec 12, 2024
b76e662
lint
angus-langchain Dec 13, 2024
efa4bd6
wait
angus-langchain Dec 13, 2024
0e06bde
signal bg threads data is available instead of sleeping
angus-langchain Dec 13, 2024
f997895
improve buffer checks
angus-langchain Dec 13, 2024
fbc217f
mypy
angus-langchain Dec 13, 2024
7b6c201
Use more threads for backend requests
angus-langchain Dec 19, 2024
35d46ed
fix futures waiting
angus-langchain Dec 19, 2024
dbef2ec
remove unused slot
angus-langchain Dec 19, 2024
6fad596
Flush background threads
angus-langchain Dec 19, 2024
5cc947a
make boundary constant
angus-langchain Dec 19, 2024
d4b2aa4
Remove slot for bool val
angus-langchain Dec 19, 2024
63e55f7
Use a single join() rather than copying the header strings
angus-langchain Dec 19, 2024
874c748
Add zstandard license
angus-langchain Dec 19, 2024
0b3d6b8
lint
angus-langchain Dec 20, 2024
7739939
Create compressed runs object
angus-langchain Dec 20, 2024
3ec9b6e
Make zstd optional
angus-langchain Dec 20, 2024
f9aac67
Make zstandard level configurable
angus-langchain Dec 20, 2024
2ac7a35
mypy ignore optional imports
angus-langchain Dec 20, 2024
3b291c3
lint
angus-langchain Dec 20, 2024
c64fb92
poetry lock
angus-langchain Dec 20, 2024
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
123 changes: 123 additions & 0 deletions python/langsmith/_internal/_background_thread.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
from __future__ import annotations

Check notice on line 1 in python/langsmith/_internal/_background_thread.py

View workflow job for this annotation

GitHub Actions / benchmark

Benchmark results

........... WARNING: the benchmark result may be unstable * the standard deviation (77.4 ms) is 11% of the mean (698 ms) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. create_5_000_run_trees: Mean +- std dev: 698 ms +- 77 ms ........... WARNING: the benchmark result may be unstable * the standard deviation (168 ms) is 12% of the mean (1.39 sec) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. create_10_000_run_trees: Mean +- std dev: 1.39 sec +- 0.17 sec ........... WARNING: the benchmark result may be unstable * the standard deviation (168 ms) is 12% of the mean (1.36 sec) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. create_20_000_run_trees: Mean +- std dev: 1.36 sec +- 0.17 sec ........... dumps_class_nested_py_branch_and_leaf_200x400: Mean +- std dev: 691 us +- 14 us ........... dumps_class_nested_py_leaf_50x100: Mean +- std dev: 24.9 ms +- 0.2 ms ........... dumps_class_nested_py_leaf_100x200: Mean +- std dev: 104 ms +- 2 ms ........... dumps_dataclass_nested_50x100: Mean +- std dev: 25.6 ms +- 0.7 ms ........... WARNING: the benchmark result may be unstable * the standard deviation (16.3 ms) is 23% of the mean (71.4 ms) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. dumps_pydantic_nested_50x100: Mean +- std dev: 71.4 ms +- 16.3 ms ........... dumps_pydanticv1_nested_50x100: Mean +- std dev: 196 ms +- 3 ms

Check notice on line 1 in python/langsmith/_internal/_background_thread.py

View workflow job for this annotation

GitHub Actions / benchmark

Comparison against main

+-----------------------------------------------+----------+------------------------+ | Benchmark | main | changes | +===============================================+==========+========================+ | dumps_pydanticv1_nested_50x100 | 220 ms | 196 ms: 1.12x faster | +-----------------------------------------------+----------+------------------------+ | create_5_000_run_trees | 731 ms | 698 ms: 1.05x faster | +-----------------------------------------------+----------+------------------------+ | create_20_000_run_trees | 1.39 sec | 1.36 sec: 1.03x faster | +-----------------------------------------------+----------+------------------------+ | create_10_000_run_trees | 1.41 sec | 1.39 sec: 1.01x faster | +-----------------------------------------------+----------+------------------------+ | dumps_class_nested_py_leaf_50x100 | 25.1 ms | 24.9 ms: 1.01x faster | +-----------------------------------------------+----------+------------------------+ | dumps_class_nested_py_branch_and_leaf_200x400 | 690 us | 691 us: 1.00x slower | +-----------------------------------------------+----------+------------------------+ | dumps_dataclass_nested_50x100 | 25.5 ms | 25.6 ms: 1.00x slower | +-----------------------------------------------+----------+------------------------+ | dumps_class_nested_py_leaf_100x200 | 104 ms | 104 ms: 1.00x slower | +-----------------------------------------------+----------+------------------------+ | dumps_pydantic_nested_50x100 | 65.9 ms | 71.4 ms: 1.08x slower | +-----------------------------------------------+----------+------------------------+ | Geometric mean | (ref) | 1.01x faster | +-----------------------------------------------+----------+------------------------+

import concurrent.futures as cf
import functools
import io
import logging
import sys
import threading
import weakref
from multiprocessing import cpu_count
from queue import Empty, Queue
from typing import (
TYPE_CHECKING,
List,
Optional,
Union,
cast,
)

import zstandard as zstd

from langsmith import schemas as ls_schemas
from langsmith._internal._constants import (
_AUTO_SCALE_DOWN_NEMPTY_TRIGGER,
Expand All @@ -30,6 +36,8 @@

logger = logging.getLogger("langsmith.client")

HTTP_REQUEST_THREAD_POOL = cf.ThreadPoolExecutor(max_workers=cpu_count() * 3)
hinthornw marked this conversation as resolved.
Show resolved Hide resolved


@functools.total_ordering
class TracingQueueItem:
Expand Down Expand Up @@ -88,6 +96,42 @@
return next_batch


def _tracing_thread_drain_compressed_buffer(
client: Client, size_limit: int = 100, size_limit_bytes: int | None = 20_971_520
) -> Optional[io.BytesIO]:
assert client.compressed_runs_buffer is not None
assert client.compressor_writer is not None
with client._buffer_lock:
current_size = client.compressed_runs_buffer.tell()

if size_limit is not None and size_limit <= 0:
raise ValueError(f"size_limit must be positive; got {size_limit}")
if size_limit_bytes is not None and size_limit_bytes < 0:
raise ValueError(
f"size_limit_bytes must be nonnegative; got {size_limit_bytes}"
)

if (size_limit_bytes is None or current_size < size_limit_bytes) and (
size_limit is None or client._run_count < size_limit
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why 100?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the limit that is currently used. It also performed well in flush time benchmarks.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can also be overridden by the batch ingest config

):
return None

# Write final boundary and close compression stream
client.compressor_writer.write(f"--{client._boundary}--\r\n".encode())
client.compressor_writer.close()

filled_buffer = client.compressed_runs_buffer

client.compressed_runs_buffer = io.BytesIO()
client.compressor_writer = zstd.ZstdCompressor(
level=3, threads=-1
).stream_writer(client.compressed_runs_buffer, closefd=False)
client._run_count = 0
angus-langchain marked this conversation as resolved.
Show resolved Hide resolved

filled_buffer.seek(0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we have a buffer we can just pass it directly to requests no? no need for iterator

return filled_buffer


def _tracing_thread_handle_batch(
client: Client,
tracing_queue: Queue,
Expand Down Expand Up @@ -200,6 +244,85 @@
_tracing_thread_handle_batch(client, tracing_queue, next_batch, use_multipart)


def tracing_control_thread_func_compress_parallel(
client_ref: weakref.ref[Client],
) -> None:
client = client_ref()
if client is None:
return

batch_ingest_config = _ensure_ingest_config(client.info)
size_limit: int = batch_ingest_config["size_limit"]
size_limit_bytes = batch_ingest_config.get("size_limit_bytes", 20_971_520)
num_known_refs = 3

def keep_thread_active() -> bool:
# if `client.cleanup()` was called, stop thread
if not client or (
hasattr(client, "_manual_cleanup") and client._manual_cleanup
):
return False
if not threading.main_thread().is_alive():
# main thread is dead. should not be active
return False
if hasattr(sys, "getrefcount"):
# check if client refs count indicates we're the only remaining
# reference to the client

# Count active threads
thread_pool = HTTP_REQUEST_THREAD_POOL._threads
active_count = sum(
1 for thread in thread_pool if thread is not None and thread.is_alive()
)

return sys.getrefcount(client) > num_known_refs + active_count
else:
# in PyPy, there is no sys.getrefcount attribute
# for now, keep thread alive
return True

while True:
triggered = client._data_available_event.wait(timeout=0.05)
if not keep_thread_active():
break
if not triggered:
continue
client._data_available_event.clear()

data_stream = _tracing_thread_drain_compressed_buffer(
client, size_limit, size_limit_bytes
)

if data_stream is not None:
try:
future = HTTP_REQUEST_THREAD_POOL.submit(
client._send_compressed_multipart_req, data_stream
)
client._futures.add(future)
except RuntimeError:
client._send_compressed_multipart_req(data_stream)

# Drain the buffer on exit
try:
final_data_stream = _tracing_thread_drain_compressed_buffer(
client, size_limit=1, size_limit_bytes=1
) # Force final drain
if final_data_stream is not None:
try:
cf.wait(
[
HTTP_REQUEST_THREAD_POOL.submit(
client._send_compressed_multipart_req, final_data_stream
)
]
)
except RuntimeError:
client._send_compressed_multipart_req(final_data_stream)

except Exception:
logger.error("Error in final cleanup", exc_info=True)


def _tracing_sub_thread_func(
client_ref: weakref.ref[Client],
use_multipart: bool,
Expand Down
31 changes: 31 additions & 0 deletions python/langsmith/_internal/_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import uuid
from typing import Literal, Optional, Union, cast

import zstandard as zstd
angus-langchain marked this conversation as resolved.
Show resolved Hide resolved

from langsmith import schemas as ls_schemas
from langsmith._internal import _orjson
from langsmith._internal._multipart import MultipartPart, MultipartPartsAndContext
Expand Down Expand Up @@ -271,3 +273,32 @@ def serialized_run_operation_to_multipart_parts_and_context(
acc_parts,
f"trace={op.trace_id},id={op.id}",
)


def compress_multipart_parts_and_context(
hinthornw marked this conversation as resolved.
Show resolved Hide resolved
parts_and_context: MultipartPartsAndContext,
compressor_writer: zstd.ZstdCompressionWriter,
boundary: str,
) -> None:
for part_name, (filename, data, content_type, headers) in parts_and_context.parts:
part_header = f"--{boundary}\r\n"
part_header += f'Content-Disposition: form-data; name="{part_name}"'
angus-langchain marked this conversation as resolved.
Show resolved Hide resolved

if filename:
part_header += f'; filename="{filename}"'

part_header += f"\r\nContent-Type: {content_type}\r\n"

for header_name, header_value in headers.items():
part_header += f"{header_name}: {header_value}\r\n"

part_header += "\r\n"
compressor_writer.write(part_header.encode())

if isinstance(data, (bytes, bytearray)):
compressor_writer.write(data)
else:
compressor_writer.write(str(data).encode())

# Write part terminator
compressor_writer.write(b"\r\n")
Loading
Loading