-
[OPIK-3511] Implement replay manager framework (#5031)
发布于
2026-02-20 14:37:15 +00:00 - [OPIK-3837] Add Connection Probe and Monitor with Unit Tests
- Introduced
ConnectionProbeto evaluate server health via lightweight probes. - Added
OpikConnectionMonitorfor monitoring server connectivity, handling state transitions (e.g., disconnect, reconnect). - Implemented comprehensive unit tests for both modules, covering edge cases and integration scenarios.
- [OPIK-3511] Refactor unit test names for improved clarity and consistency
- Updated test function names in
test_connection_monitor.pyandtest_connection_probe.pyto follow consistent and descriptive naming conventions. - Consolidated repetitive test cases in
test_connection_probe.pyusing parameterization to reduce redundancy.
- [OPIK-3511] Refactor
OpikConnectionMonitorto simplify state management
- Replaced
_last_beatwithlast_beatas a public instance variable. - Updated unit tests in
test_connection_monitor.pyto reflect the changes. - Improved naming consistency across
ConnectionMonitorimplementation and tests.
- [OPIK-3837] Refactor
ConnectionProbeerror handling and update related tests
- Consolidated
httpx.ConnectErrorandhttpx.TimeoutExceptioninto a single handler with updated error messaging for clarity. - Simplified test cases by reusing error variables and ensuring consistency in assertions for error messages.
- Added log verification for unexpected exceptions in
test_check_connection__unexpected_exception.
- [OPIK-3837] Refactor
message_processingmodule and addReplayManager
- Added
ReplayManagerfor handling message lifecycle (registering, updating, replaying failed messages). - Introduced
message_typeattribute to all message classes for consistent identification. - Added
from_db_message_dictfor easier conversion of dictionary data to message objects. - Refactored
BaseMessageserialization methods to support additional attributes.
- [OPIK-3837] Enhance
OpikConnectionMonitorconnection handling and updatetickdocstring
- Added
_has_server_connectionreset logic inresetmethod to ensure clean state initialization. - Updated
tickmethod docstring for improved clarity around connection monitoring behavior and return values.
- [OPIK-3837] Add comprehensive unit tests and enhance serialization for
message_processingmodule
- Added extensive unit tests covering serialization/deserialization for all core message types, including nested objects.
- Improved
from_db_message_dictto handle fields withinit=False. - Enhanced message classes (
AddFeedbackScoresBatchMessage,CreateTraceBatchMessage, etc.) with_deserializeand_serializemethods for batch processing. - Updated
ReplayManagerto register additional message types.
- [OPIK-3837] Add JSON-based serialization/deserialization for messages and update tests
- Refactored serialization logic to serialize messages to JSON strings and deserialize them back via
message_serializationmodule. - Replaced
AttachmentSupportingMessagewithCreateAttachmentMessagefor streamlined handling. - Updated
ReplayManagerto utilizeserialize_messageanddeserialize_messagefunctions. - Renamed and expanded test functions for detailed coverage of JSON-based round-trip serialization.
- [OPIK-3837] Enhance
ReplayManagerwith batch processing and improve error handling
- Introduced a
batch_sizeparameter with a default value of 1000 for efficient batch processing of messages. - Added
_fetch_failed_messages_batchedfor cursor-based pagination of failed messages to avoid OOM issues. - Updated
register_messagesandreplay_failed_messagesto support batch operations. - Improved logging by including exception details for better debugging.
- Ensured database schema creation uses
IF NOT EXISTSfor idempotency.
- [OPIK-3837] Add
batch_replay_delaytoReplayManagerand improve batch processing
- Introduced
batch_replay_delayparameter to control delays between batch replays for better memory management. - Renamed
ReplayManager._fetch_failed_messages_batchedtofetch_failed_messages_batchedfor public access. - Fixed SQL typo in
CREATE TABLEstatement. - Added tests for
ReplayManagerto validate new batch replay logic, including delay handling and batch processing behavior. - Enhanced error handling for file cleanup in
_clean_message_leftovers.
- [OPIK-3837] Add tests for
datetime_object_hookand improve datetime handling
- Implemented unit tests for
datetime_object_hookto ensure proper conversion of known datetime fields while preserving non-datetime fields. - Introduced
DATETIME_FIELD_NAMESto restrict datetime conversions to specific fields, preventing accidental conversions of ISO-like strings. - Updated related deserialization logic to use the new
datetime_object_hook.
- [OPIK-3837] Add detailed docstrings to
ReplayManagermethods for clarity
- Included comprehensive docstrings for all public and critical methods in
ReplayManagerto improve readability and maintainability. - Documented arguments, return values, and method functionality, ensuring clear usage guidelines for developers.
- [OPIK-3837] Refactor file upload flow and remove
FileUploadPreprocessor
- Replaced
FileUploadPreprocessorwithFileUploadManagerfor improved attachment handling. - Updated
OpikClientandStreamerto directly utilizeFileUploadManagerwithout the intermediary preprocessor. - Refactored related unit tests to mock and test
FileUploadManager. - Simplified message processing by removing redundant file upload preprocessor logic.
-
[OPIK-3837] Updated design docs
-
[OPIK-3837] Fixed linter errors
-
[OPIK-3838] Implement integration of replay manager with Opik message processing (#5195)
-
[OPIK-3838] Refactor
ReplayManagertoDBManagerand update dependencies
- Renamed
ReplayManagertoDBManagerfor better alignment with its database management responsibilities. - Updated all references, imports, and tests to reflect the new class name.
- Standardized usage of
DBManagerStatusinstead ofManagerStatusfor state tracking.
- [OPIK-3838] Add
ReplayManagerfor handling offline message replay
- Introduced
ReplayManagerto manage the replay of failed messages when the connection is restored. - Added
ReplayCallbacktype definition for defining replay logic. - Enhanced
DBManagerto integrate withReplayManagervia callback handling.
- [OPIK-3838] Add
ReplayManagerfor handling offline message replay
- Introduced
ReplayManagerto manage the replay of failed messages when the connection is restored. - Added
ReplayCallbacktype definition for defining replay logic. - Enhanced
DBManagerto integrate withReplayManagervia callback handling.
- [OPIK-3838] Refactor
ReplayManagerinitialization and optimize tick loop
- Updated
ReplayManagerto acceptDBManageras a constructor parameter, improving dependency injection. - Refined
_loopmethod to include sleep logic, reducing CPU usage during idle periods. - Enhanced
DBManagerto correctly handleMessageStatuswhen processing messages.
- [OPIK-3895] Refactor
ReplayManagerfor improved synchronization and reliability
- Added new defaults for
batch_size,batch_replay_delay, andtick_interval_secondsinReplayManager. - Introduced
threading.RLockfor synchronized message replay and integrated it withDBManager. - Enhanced
_loopmethod with interruptible sleep viathreading.Eventfor clean shutdown. - Improved error handling and message replay logic, ensuring failed messages are properly updated.
- [OPIK-4321] Add unit tests for
ReplayManager
- Introduced comprehensive test suite for
ReplayManagercovering initialization, message registration, reconciliation, and lifecycle management. - Validated functionality across scenarios including failed messages, connection restoration, and concurrency handling.
- [OPIK-3838] Add
db_managerproperty toReplayManagerand update tests
- Introduced
db_managerproperty for cleaner access to the database manager. - Refactored test cases to use the new property, improving code readability.
- [OPIK-3838] Refine test to validate loop behavior with replay callback errors
- Updated test name for better clarity.
- Adjusted test to simulate connection restoration and ensure thread resilience to replay callback errors.
- [OPIK-3838] Add
failed_messages_countmethod toDBManagerand integrate withStreamer
- Implemented
failed_messages_countinDBManagerto retrieve the count of failed messages. - Added unit tests to verify behavior across various scenarios, including initialization, mixed statuses, and database errors.
- Integrated
ReplayManagerwithStreamer, enabling replay callback handling and lifecycle management. - Updated
Streamerto closeReplayManagergracefully and handle failed message replay during shutdown.
- [OPIK-3838] Integrate
ReplayManagerintoStreamerand add lifecycle unit tests
- Connected
ReplayManagertoStreamerfor fallback processing of failed messages. - Added unit and integration tests to validate
ReplayManagerinteraction withStreamerlifecycle events (init, flush, close). - Introduced configuration options for replay-related parameters such as batch size, delay, and tick interval.
- Refactored constructors and fixtures to support
ReplayManagerinjection.
- [OPIK-3838] Add unit tests for
OpikMessageProcessorwithReplayManagerintegration
- Added test coverage for
OpikMessageProcessormethods interacting withReplayManager, including message registration, unregistration, and error handling. - Enhanced error handling in
ReplayManagerandDBManagerto log failures and raise appropriate exceptions. - Updated process lifecycle for better resilience under connection failures and server errors.
- Adjusted
ReplayManagerto handle failed messages gracefully, ensuring unprocessed messages remain registered for retries.
- [OPIK-3838] Fixed typo
- Added test coverage for
OpikMessageProcessormethods interacting withReplayManager, including message registration, unregistration, and error handling. - Enhanced error handling in
ReplayManagerandDBManagerto log failures and raise appropriate exceptions. - Updated process lifecycle for better resilience under connection failures and server errors.
- Adjusted
ReplayManagerto handle failed messages gracefully, ensuring unprocessed messages remain registered for retries.
- [OPIK-3838] Add message ID validation in
ReplayManagerand update references
- Introduced
_check_message_idmethod inReplayManagerto validate message IDs in critical methods. - Updated
OpikMessageProcessorto include type ignores for MyPy compliance. - Ensured robust error handling by verifying message ID presence at registration, unregistration, and failure points.
- [OPIK-3838] Automatically assign message IDs in
ReplayManagerif missing
- Added logic to auto-assign unique message IDs when registering messages with missing IDs.
- Extended unit tests to confirm correct ID assignment and database registration behavior.
- [OPIK-3838] Add offline fallback handling and refactor
ReplayManagerinteractions
- Introduced offline handling in
OpikMessageProcessorto register messages as failed when there is no server connection. - Added unit tests for offline scenarios to validate message registration and ensure handlers are not invoked without connectivity.
- Renamed
db_managertodatabase_managerinReplayManagerfor improved clarity. - Updated related methods and test cases to reflect the renamed property.
- Enhanced
ReplayManagerto support message registration with specific statuses, includingMessageStatus.failed.
- [OPIK-3838] Add upload success and failure callbacks across file upload flow
- Enhanced file upload system to support
on_upload_successandon_upload_failedcallbacks. - Updated related classes and methods, including
BaseFileUploadManager,DBManager, andOpikMessageProcessor. - Introduced callback types and modified
uploadmethod signatures. - Updated S3 error handling to distinguish connection errors.
- Added unit tests for callback integration and error scenarios.
- [OPIK-3838] Add error handling and unit tests for message replay and attachment uploads
- Enhanced
OpikMessageProcessorwith additional error handling for API errors, validation errors, retry errors, and generic exceptions during message processing. - Added robust unit tests to validate
ReplayManagercallbacks and message state changes across various error scenarios. - Introduced support for attachment upload callbacks (
on_upload_successandon_upload_failed), validating their interactions with the replay lifecycle. - Updated file uploader methods to accept upload callbacks and modified related test cases to align with the changes.
-
[OPIK-3838] Reduced unnecessary large sleep times to reduce test execution time
-
[OPIK-3838] Refactor message registration and processing logic in
OpikMessageProcessor
- Simplified
ReplayManagerinteraction for message registration based on server connection status. - Consolidated logic to ensure proper handling of
CreateAttachmentMessageand other message types. - Updated file upload callbacks with type ignores for MyPy compliance.
- [OPIK-3838] Remove unnecessary sleep in UUID generation for unit tests
- Replaced
time.sleepwith timestamp generation usingdatetime.fromtimestampto improve test execution speed.
- [OPIK-3511] Remove default parameter values from
ReplayManagerconstructor
- Eliminated default values for
batch_size,batch_replay_delay, andtick_interval_secondsinReplayManagerto enforce explicit configuration.
- [OPIK-3511] Add upsert behavior for message registration in
DBManager
- Modified
register_messageandregister_messagesto useON CONFLICTfor updating existing records. - Enhanced unit tests to validate upsert functionality for single and batch message operations.
- [OPIK-3511] Add ignored message types handling in
OpikMessageProcessor
- Introduced
_ignored_message_types_for_replayto bypass replay registration for specific message types. - Added
_should_ignore_replay_for_message_typehelper method for streamlined type checking. - Updated processing logic to skip replay manager interaction for ignored types while ensuring handler execution.
- Enhanced unit tests to verify correct behavior for ignored types under online and offline conditions.
- Fixed typo in replay log message ("was" to "were").
- Added explicit configuration options to
ReplayManagerin tests forbatch_size,batch_replay_delay, andtick_interval_seconds.
- [OPIK-3511] Ensure
DBManageris properly closed after assertion in unit test
- Added a
finallyblock to closeDBManagerafter theassertstatement to ensure resource cleanup.
- [OPIK-4132] Enhance thread-safety and concurrency handling in
DBManager
- Introduced
_replay_mutexto prevent concurrentreplay_failed_messagescalls from duplicating message fetches. - Modified lock logic to ensure
self.__lock__is only held for critical sections, avoiding blockage of producers during replay callbacks or delays. - Added unit tests to verify concurrency behavior, ensuring producers remain unblocked during sleep and callbacks.
- Improved documentation in
replay_failed_messagesto clarify locking strategy and concurrency guarantees. - Updated unit tests to validate lock behavior during multi-threaded operations.
- [OPIK-3511] Refactor locking and synchronization in
ReplayManager
- Replaced
_replay_lockwith_message_id_lockfor improved thread-safety during message registration. - Removed unnecessary locking around
_replay_failed_messagesto simplify synchronization and improve efficiency. - Updated
DBManagerinitialization to remove dependency on shared locks.
- [OPIK-3511] Improve message replay handling and add E2E test coverage
- Fixed
strip()logic in feedback reason handling to avoid errors whenreasonis None. - Adjusted replay log message for proper singular/plural grammar.
- Added comprehensive E2E tests for offline fallback and failed message replay functionalities.
- [OPIK-3511] Improve thread-safety in
fetch_failed_messages_batchedand fix test fixture docstrings
- Wrapped
fetch_failed_messages_batchedlogic withself.__lock__to ensure proper synchronization during database operations. - Fixed incorrect docstrings in test fixtures to refer to
DBManagerinstead ofReplayManager.
-
[OPIK-3511] Fixed docstring for batch_size
-
[OPIK-3511] Fixed docstring for DBManager.closed property
-
[OPIK-3511] Fixed docstring for DBManager
-
[OPIK-3511] Update e2e tests to include batching and ensure correct replay behavior
- Refactored
non_batching_opik_clienttonot_batching_opik_clientfor naming consistency. - Added comprehensive e2e test cases for batching mode: replaying
CreateTraceBatchMessage,CreateSpansBatchMessage, feedback score batches, and simultaneous offline operations. - Verified attachment-related operations in both batching and non-batching modes.
- Updated and clarified docstrings across tests.
- [OPIK-3511] Add E2E test for
CreateExperimentItemsBatchMessagereplay and refactor attachment usage
- Introduced a new E2E test to verify the successful replay of
CreateExperimentItemsBatchMessagestored during offline mode. - Refactored
Attachmentreferences to useattachment.Attachmentfor consistency and improved readability. - Updated imports to accommodate the new test case enhancements.
-
[OPIK-3511] Added additional debug logging for DBManager for clarity
-
[OPIK-3839] Write documentation about offline fallback (#5316)
-
[OPIK-3839] Add documentation for offline fallback and message replay feature
- Introduced new section on offline fallback and message replay in
docs.yml. - Added detailed documentation outlining the offline fallback mechanism, supported message types, configuration options, and troubleshooting steps.
- [OPIK-3839] Update tracing documentation to include
log_threads_feedback_scores
- Added
client.log_threads_feedback_scores()mapping toAddThreadsFeedbackScoresBatchMessagein supported message types table.
-
[OPIK-3838] Added commentary to explain the need for OpikMessageProcessor._ignored_message_types_for_replay field
-
[OPIK-3838] Ensure UTC timezone is explicitly set for datetime fields in serialization tests and update JSON encoding logic
- Updated unit tests to include
tzinfo=datetime.timezone.utcfor datetime fields to ensure consistent handling of timezone information. - Replaced
MessageJSONEncoderwithjsonable_encoder.encodefor improved JSON serialization logic.
- [OPIK-3838] Add tests for non-JSON-serializable types and cyclic references in message serialization
- Introduced
TestNonJsonSerializableTypesInMessageFieldswith cases for handling non-serializable fields like bytes, sets, tuples, and numpy arrays. - Verified proper serialization of datetime, custom classes, and cyclic references without crashes.
- Updated
serialize_messagelogic to leveragejsonable_encoder.encodefor robust encoding of special field types.
- [OPIK-3838] Ensure datetime fields in DBManager tests explicitly include UTC timezone
- Updated
test_db_manager.pyto settzinfo=datetime.timezone.utcforstart_timeandend_timedatetime fields in unit tests.
下载附件