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

feat(weave): Add sync/async generator support #3879

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

andrewtruong
Copy link
Collaborator

@andrewtruong andrewtruong commented Mar 16, 2025

Adds basic sync and async generator tracing support

See example for code:

from typing import Generator


@weave.op
def basic_gen(x: int) -> Generator[int, None, None]:
    yield from range(x)


@weave.op
def inner(x: int) -> int:
    return x + 1


@weave.op
def nested_generator(x: int) -> Generator[int, None, None]:
    for i in range(x):
        yield inner(i)


@weave.op
def deeply_nested_generator(x: int) -> Generator[int, None, None]:
    for i in range(x):
        for j in nested_generator(i):
            yield j


res = deeply_nested_generator(4)
list(res)

image

Summary by CodeRabbit

  • Refactor

    • Overhauled internal processing for asynchronous and streaming operations to improve error management and overall reliability.
    • Standardized the handling of accumulation across various integrations for a more consistent user experience.
  • Tests

    • Updated test cases to validate the refined behavior in both synchronous and asynchronous scenarios, ensuring robust and stable performance.

Copy link
Contributor

github-actions bot commented Mar 16, 2025

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@circle-job-mirror
Copy link

@andrewtruong andrewtruong changed the base branch from master to andrew/lifecycle0a March 16, 2025 17:38
Copy link
Contributor

coderabbitai bot commented Mar 16, 2025

Walkthrough

This pull request refactors the accumulator functionality by renaming the public function add_accumulator to _add_accumulator across multiple test files and integration SDK wrappers. The related import statements have been updated accordingly. In addition, significant modifications have been made in weave/trace/op.py to enhance tracing capabilities for synchronous, asynchronous, and generator-based operations, including improved error handling and context management. Finally, the legacy accumulator module in weave/trace/op_extensions/accumulator.py has been removed.

Changes

File(s) Change Summary
tests/trace/test_op_return_forms.py, tests/trace/test_tracing_resilience.py Renamed accumulator usage: replaced add_accumulator with _add_accumulator and updated import statements.
weave/integrations/anthropic/anthropic_sdk.py, weave/integrations/bedrock/bedrock_sdk.py, weave/integrations/cohere/cohere_sdk.py, weave/integrations/google_ai_studio/google_ai_studio_sdk.py, weave/integrations/groq/groq_sdk.py, weave/integrations/huggingface/huggingface_inference_client_sdk.py, weave/integrations/instructor/instructor_iterable_utils.py, weave/integrations/instructor/instructor_partial_utils.py, weave/integrations/langchain_nvidia_ai_endpoints/langchain_nv_ai_endpoints.py, weave/integrations/litellm/litellm.py, weave/integrations/mistral/v0/mistral.py, weave/integrations/mistral/v1/mistral.py, weave/integrations/openai/openai_sdk.py, weave/integrations/vertexai/vertexai_sdk.py Updated wrappers and SDK functions by replacing add_accumulator with _add_accumulator and adjusting the module import paths.
weave/trace/op.py Enhanced tracing system with new utility functions (_should_skip_tracing, _should_sample_traces), refactored synchronous and asynchronous call functions, and improved error handling with updated type annotations.
weave/trace/op_extensions/accumulator.py Removed legacy accumulator module including its accumulator classes and iterator wrappers.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Client as User/Application
    participant Decorator as op Decorator
    participant Tracer as Tracing Functions
    participant Acc as _add_accumulator
    Client->>Decorator: Call operation
    Decorator->>Tracer: Check tracing conditions (_should_skip_tracing/_should_sample_traces)
    Tracer-->>Decorator: Return operation result
    Decorator->>Acc: Invoke accumulator wrapping
    Acc-->>Decorator: Return accumulated result
    Decorator-->>Client: Return final processed output
Loading
sequenceDiagram
    participant Wrapper as Integration SDK Wrapper
    participant Acc as _add_accumulator
    participant Operation as Underlying Operation
    Wrapper->>Acc: Call _add_accumulator(op, lambda)
    Acc->>Operation: Execute operation
    Operation-->>Acc: Return result
    Acc-->>Wrapper: Return accumulated result

Poem

I'm a little rabbit, hopping around the code,
Changing names and paths on every tracing road.
From add_accumulator to a secret _add so neat,
I nibble on bugs and make each test complete.
With hops of joy and bytes galore, my code garden blooms—
A magical maze of fixes that banishes old glooms!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 34defc9 and ef0484d.

📒 Files selected for processing (18)
  • tests/trace/test_op_return_forms.py (17 hunks)
  • tests/trace/test_tracing_resilience.py (11 hunks)
  • weave/integrations/anthropic/anthropic_sdk.py (4 hunks)
  • weave/integrations/bedrock/bedrock_sdk.py (2 hunks)
  • weave/integrations/cohere/cohere_sdk.py (3 hunks)
  • weave/integrations/google_ai_studio/google_ai_studio_sdk.py (3 hunks)
  • weave/integrations/groq/groq_sdk.py (2 hunks)
  • weave/integrations/huggingface/huggingface_inference_client_sdk.py (3 hunks)
  • weave/integrations/instructor/instructor_iterable_utils.py (3 hunks)
  • weave/integrations/instructor/instructor_partial_utils.py (2 hunks)
  • weave/integrations/langchain_nvidia_ai_endpoints/langchain_nv_ai_endpoints.py (2 hunks)
  • weave/integrations/litellm/litellm.py (2 hunks)
  • weave/integrations/mistral/v0/mistral.py (2 hunks)
  • weave/integrations/mistral/v1/mistral.py (2 hunks)
  • weave/integrations/openai/openai_sdk.py (3 hunks)
  • weave/integrations/vertexai/vertexai_sdk.py (3 hunks)
  • weave/trace/op.py (11 hunks)
  • weave/trace/op_extensions/accumulator.py (0 hunks)
💤 Files with no reviewable changes (1)
  • weave/trace/op_extensions/accumulator.py
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.py`: Focus on pythonic code patterns. Check for proper...

**/*.py: Focus on pythonic code patterns.
Check for proper exception handling.
Verify type hints usage where applicable.
Look for potential performance improvements.
Don't comment on formatting if black/isort is configured.
Check for proper dependency injection patterns.
Verify proper async handling if applicable.

  • weave/integrations/google_ai_studio/google_ai_studio_sdk.py
  • weave/integrations/mistral/v0/mistral.py
  • weave/integrations/instructor/instructor_partial_utils.py
  • weave/integrations/openai/openai_sdk.py
  • weave/integrations/mistral/v1/mistral.py
  • weave/integrations/bedrock/bedrock_sdk.py
  • weave/integrations/langchain_nvidia_ai_endpoints/langchain_nv_ai_endpoints.py
  • weave/integrations/anthropic/anthropic_sdk.py
  • weave/integrations/groq/groq_sdk.py
  • weave/integrations/litellm/litellm.py
  • weave/integrations/cohere/cohere_sdk.py
  • tests/trace/test_tracing_resilience.py
  • weave/integrations/instructor/instructor_iterable_utils.py
  • weave/integrations/huggingface/huggingface_inference_client_sdk.py
  • weave/integrations/vertexai/vertexai_sdk.py
  • weave/trace/op.py
  • tests/trace/test_op_return_forms.py
⏰ Context from checks skipped due to timeout of 90000ms (106)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, llamaindex)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, llamaindex)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, llamaindex)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, llamaindex)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, llamaindex)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, llamaindex)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
  • GitHub Check: Trace nox tests (3, 13, llamaindex)
  • GitHub Check: Trace nox tests (3, 13, trace)
  • GitHub Check: Trace nox tests (3, 12, scorers)
  • GitHub Check: Trace nox tests (3, 12, llamaindex)
  • GitHub Check: Trace nox tests (3, 12, trace)
  • GitHub Check: Trace nox tests (3, 11, scorers)
  • GitHub Check: Trace nox tests (3, 11, trace)
  • GitHub Check: Trace nox tests (3, 10, scorers)
  • GitHub Check: Trace nox tests (3, 10, trace)
  • GitHub Check: Trace nox tests (3, 9, scorers)
🔇 Additional comments (56)
weave/integrations/instructor/instructor_partial_utils.py (2)

7-7: Appropriate renaming of imported function to match new convention.

The change from importing add_accumulator to _add_accumulator correctly aligns with the refactored function in weave.trace.op. The underscore prefix indicates this is now an internal implementation detail rather than a public API.


22-26: Updated function call with correct parameters.

The function call was properly updated to use _add_accumulator instead of add_accumulator while maintaining the same parameter structure. This change is consistent with the function's new signature in the weave.trace.op module.

weave/integrations/google_ai_studio/google_ai_studio_sdk.py (3)

10-10: Correctly updated import for refactored accumulator function.

The import has been properly updated to reference the renamed _add_accumulator function from its new location in weave.trace.op module.


103-108: Updated function call in gemini_wrapper_sync to use new API.

The function call has been correctly updated to use _add_accumulator instead of add_accumulator, maintaining the same parameter structure and logic for streaming accumulation.


128-133: Updated function call in gemini_wrapper_async to use new API.

The function call has been correctly updated to use _add_accumulator instead of add_accumulator in the async wrapper, maintaining consistent behavior with the synchronous version.

weave/integrations/bedrock/bedrock_sdk.py (2)

4-4: Correctly updated import for both refactored functions.

The import has been properly updated to reference both _add_accumulator and _IteratorWrapper from their new location in the weave.trace.op module.


136-141: Updated function call with all required parameters.

The function call has been correctly updated to use _add_accumulator instead of add_accumulator, maintaining the same parameter structure including the custom BedrockIteratorWrapper class for proper stream handling.

weave/integrations/mistral/v0/mistral.py (2)

9-9: Correctly updated import for refactored accumulator function.

The import has been properly updated to reference the renamed _add_accumulator function from its new location in the weave.trace.op module.


84-84:

❓ Verification inconclusive

Updated function call but retain type ignore comment.

The function call has been correctly updated to use _add_accumulator. The type ignore comment is still present, which is appropriate if there are known type checking limitations with this integration.

Verify that the type ignore comment is still necessary with the renamed function. If you're facing type-checking issues, consider adding proper type annotations instead:


🏁 Script executed:

#!/bin/bash
# Check if mypy is configured for the project and if it gives errors for this line
if [ -f "pyproject.toml" ]; then
  echo "Checking if mypy is configured in pyproject.toml:"
  grep -A 10 "\[tool.mypy\]" pyproject.toml
fi

# Check if there are type annotations for mistral_accumulator
echo "Looking for type annotations for mistral_accumulator:"
rg -A 3 "def mistral_accumulator" --type py

Length of output: 1217


Action Required: Confirm Type Annotation for Accumulator Function

  • The updated call to _add_accumulator now correctly passes a lambda returning mistral_accumulator, and our check confirms that mistral_accumulator is fully annotated.
  • The project’s mypy configuration (in pyproject.toml) is present and properly set up.
  • However, since the lambda “wrapper” still returns the function without invoking it—and given that the typing for _add_accumulator isn’t fully verified here—the # type: ignore comment remains until you’re certain mypy no longer raises issues.
  • Please re-run mypy on this change to confirm whether the ignore comment can eventually be removed or if additional type annotations around the accumulator call are warranted.
weave/integrations/vertexai/vertexai_sdk.py (3)

10-10: Import updated to reflect new module location.

The import statement has been updated to use _add_accumulator from weave.trace.op instead of the deprecated add_accumulator from the accumulator extension module. This change aligns with moving this functionality to the core op module and marking it as an internal implementation detail.


98-103: Function call updated to use internal accumulator API.

The renamed _add_accumulator function is now being properly used in the vertexai_wrapper_sync function. The functionality remains the same, but the naming change clearly indicates this is an internal API not meant for general use outside of integration code.


123-128: Function call updated to use internal accumulator API.

Similar to the sync wrapper, the async wrapper now correctly uses _add_accumulator with consistent parameters. This maintains the same accumulator logic while reflecting the architectural change.

weave/integrations/litellm/litellm.py (2)

9-9: Import updated to use internal implementation.

The import has been updated to use _add_accumulator from the consolidated location in weave.trace.op module instead of the previous accumulator extension.


94-99: Function call updated to use internal accumulator API.

The _add_accumulator function is now being properly used in the litellm_wrapper function, maintaining the same functionality while reflecting the architectural change to use an internal API.

weave/integrations/huggingface/huggingface_inference_client_sdk.py (3)

8-8: Import updated to use internal implementation.

The import statement has been updated to use _add_accumulator from the core weave.trace.op module, aligning with the architectural changes to consolidate accumulator functionality.


82-87: Function call updated to use internal accumulator API.

The huggingface_wrapper_sync function now correctly uses _add_accumulator instead of the deprecated add_accumulator, maintaining consistent behavior while following the new implementation pattern.


106-111: Function call updated to use internal accumulator API.

The async wrapper implementation has been updated to use _add_accumulator, keeping the same functionality while adapting to the architectural changes.

weave/integrations/instructor/instructor_iterable_utils.py (3)

8-8: Import updated to use internal implementation.

The import statement has been updated to use _add_accumulator from the main weave.trace.op module instead of the deprecated accumulator extension module.


35-39: Function call updated to use internal accumulator API.

The sync wrapper now correctly uses _add_accumulator instead of the deprecated public function, maintaining the same behavior while following the new implementation pattern.


55-59: Function call updated to use internal accumulator API.

The async wrapper implementation has been updated to use _add_accumulator, ensuring consistent usage of the internal API across both synchronous and asynchronous contexts.

weave/integrations/openai/openai_sdk.py (3)

10-10: Refactoring of public API to internal API

The import has been updated from add_accumulator to _add_accumulator, which properly reflects that this function is meant for internal use only as indicated by its docstring.


334-341: Function renamed to clarify internal use

The function call has been updated from add_accumulator to _add_accumulator to indicate that this is an internal function not meant for general public use. The function signature and parameters remain unchanged, preserving the existing behavior.


370-377: Function renamed to clarify internal use

Similar to the sync version, the function call has been updated from add_accumulator to _add_accumulator in the async wrapper implementation. The function signature and parameters remain unchanged, preserving the existing behavior.

weave/integrations/anthropic/anthropic_sdk.py (4)

11-11: Updated import to use internal API function

The import has been updated from add_accumulator to _add_accumulator, which properly reflects that this function is meant for internal use only. Also imported _IteratorWrapper which is used in the AnthropicIteratorWrapper class.


80-84: Function renamed to clarify internal use

The function call has been updated from add_accumulator to _add_accumulator to indicate that this is an internal function. The function signature and parameters remain unchanged, preserving the existing behavior.


104-108: Function renamed to clarify internal use

The function call has been updated from add_accumulator to _add_accumulator in the async wrapper implementation. The function signature and parameters remain unchanged, preserving the existing behavior.


173-178: Function renamed to clarify internal use

The function call has been updated from add_accumulator to _add_accumulator in the stream wrapper implementation. The function signature, parameters, and custom iterator wrapper remain unchanged, preserving the existing behavior.

weave/integrations/groq/groq_sdk.py (2)

9-9: Updated import to use internal API function

The import has been updated from add_accumulator to _add_accumulator, which properly reflects that this function is meant for internal use only as indicated by its docstring.


96-100: Function renamed to clarify internal use

The function call has been updated from add_accumulator to _add_accumulator to indicate that this is an internal function. The function signature and parameters remain unchanged, preserving the existing behavior.

weave/integrations/mistral/v1/mistral.py (2)

9-9: Updated import to use internal API function

The import has been updated from add_accumulator to _add_accumulator, which properly reflects that this function is meant for internal use only as indicated by its docstring.


91-91: Function renamed to clarify internal use

The function call has been updated from add_accumulator to _add_accumulator to indicate that this is an internal function. The function signature and parameters remain unchanged, preserving the existing behavior.

weave/integrations/langchain_nvidia_ai_endpoints/langchain_nv_ai_endpoints.py (2)

17-17: Import refactored module path and function name

The import has been updated to use _add_accumulator from weave.trace.op instead of potentially importing it from a different module. This reflects the refactoring of the accumulator functionality.


164-169: Function name updated to use internal API

The function call has been updated to use _add_accumulator instead of add_accumulator. This maintains the same functionality but uses the renamed internal API.

tests/trace/test_op_return_forms.py (2)

4-4: Updated import to use internal API

The import statement has been updated to use _add_accumulator from weave.trace.op instead of the previously imported add_accumulator function. This aligns with the refactoring of the accumulator functionality.


113-113: Updated function calls to use internal API

All calls to add_accumulator have been consistently replaced with _add_accumulator. This test file thoroughly verifies both synchronous and asynchronous generator support, covering various scenarios including:

  • Complete iteration
  • Partial iteration
  • Never iterated cases
  • Exception handling

The comprehensive test coverage ensures the refactored functionality works correctly.

Also applies to: 140-140, 175-175, 211-211, 237-237, 263-263, 297-297, 332-332, 357-357, 385-385, 421-421, 458-458

weave/integrations/cohere/cohere_sdk.py (2)

10-10: Updated import to use internal API

The import statement has been updated to use _add_accumulator from weave.trace.op instead of importing from a different module. This reflects the refactoring of the accumulator functionality.


170-170: Updated function calls to use internal API

The function calls in cohere_stream_wrapper and cohere_stream_wrapper_v2 have been updated to use _add_accumulator instead of add_accumulator. This maintains the same functionality while using the refactored internal API.

Also applies to: 179-179

tests/trace/test_tracing_resilience.py (2)

17-17: Updated import to use internal API

The import statement has been updated to use _add_accumulator from weave.trace.op instead of importing from a different module. This reflects the refactoring of the accumulator functionality.


146-146: Updated function calls to use internal API

All calls to add_accumulator have been consistently replaced with _add_accumulator. These tests thoroughly validate error handling and resilience in different scenarios with both synchronous and asynchronous generators, including:

  • Errors in accumulator creation
  • Errors during accumulation
  • Errors in should_accumulate predicate
  • Errors in post-processing callbacks

The test coverage ensures that the refactored functionality maintains proper error handling.

Also applies to: 181-181, 214-214, 254-254, 293-297, 385-389, 431-435, 470-470, 500-500

weave/trace/op.py (17)

5-5: Use caution with atexit usage.
In multi-process or short-lived environments, atexit handlers may not always execute as intended. Verify that relying on atexit-driven cleanup aligns with your deployment constraints.


11-12: New imports look fine.
These standard library imports from weakref and collections.abc appear appropriate.


20-20: Introduction of Generic and TypeVar.
Using Generic and TypeVar is a good way to add type safety to your ops.

Also applies to: 24-24


67-68: Generics for accumulating state.
Defining S and V is a sound approach for typed, generic state accumulation.


71-84: Polyfill for Python < 3.10.
The fallback implementations for aiter and anext are consistent with Python 3.10 behavior.


86-86: Logger instantiation.
No concerns about creating a logger at this module level.


299-309: Skip-tracing logic.
Conditionally skipping tracing based on settings and client context looks appropriate.


321-332: Placeholder call object.
Creating a minimal Call placeholder is straightforward and matches the usage pattern in downstream code.


334-419: Synchronous function tracing.
The logic for skipping or sampling traces is coherent. Ensure consistency with the _should_sample_traces naming/behavior so as not to confuse developers.


422-558: Synchronous generator support.
Push/pop of call context, accumulator handling, and iteration flow appear solid for sync generators.


560-644: Asynchronous function tracing.
This mirrors _call_sync_func closely. Error handling and context finalization appear robust.


646-787: Asynchronous generator handling.
Providing state accumulation and correct cleanup for async generators is well-implemented.


789-843: Central call function.
Dynamically invoking the appropriate _call_* variant ensures flexible support for sync, async, and generator functions.


1102-1273: _IteratorWrapper finalization.
Registering _call_on_close_once with atexit can help ensure cleanup, but consider verifying behavior in multi-process or ephemeral runtime scenarios.


1274-1298: _Accumulator class.
This incremental approach to state accumulation is concise and straightforward.


1299-1317: _build_iterator_from_accumulator_for_op helper.
Constructing an iterator wrapper with a finish callback cleanly integrates the accumulator mechanism.


1319-1375: _add_accumulator for streaming ops.
Associating an accumulator function to handle streamed outputs looks well-designed for integrative scenarios.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Sorry, something went wrong.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (1)
weave/trace/op.py (1)

915-1001: Op decorator wrapper.
Though effective, you may consider a refactor to reduce the duplicated logic between sync/async generator creation.

🛑 Comments failed to post (1)
weave/trace/op.py (1)

311-319: ⚠️ Potential issue

Potential name/logic inconsistency in _should_sample_traces.
Currently, returning True causes tracing to be disabled via tracing_disabled(). The name suggests the opposite. Consider inverting the condition or renaming the function to avoid confusion.

Possible fix:

-    if random.random() > op.tracing_sample_rate:
-        return True  # Sample traces for this call
-    return False
+    if random.random() <= op.tracing_sample_rate:
+        return True  # Sample the tracing
+    return False
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

def _should_sample_traces(op: Op) -> bool:
    if call_context.get_current_call():
        return False  # Don't sample traces for child calls

    if random.random() <= op.tracing_sample_rate:
        return True  # Sample the tracing
    return False

@andrewtruong andrewtruong force-pushed the andrew/lifecycle0a branch 2 times, most recently from 5cc880c to 93b7c4c Compare March 18, 2025 19:22
Base automatically changed from andrew/lifecycle0a to master March 19, 2025 16:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant