-
Notifications
You must be signed in to change notification settings - Fork 559
chore(types): Type-clean logging (43 errors) #1395
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
Conversation
|
Converting to draft while I rebase on the latest changes to develop. |
033dc0f to
2df17d7
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
Marking ready-for-review after rebasing on top of develop. Please review when you have time @Pouyanpi , @trebedea , @cparisien |
trebedea
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good 👍
Signed-off-by: Tim Gasser <[email protected]>
* Cleaned logging directory * Add nemoguardrails/logging to pyright pre-commit checks --------- Signed-off-by: Tim Gasser <[email protected]>
* Cleaned logging directory * Add nemoguardrails/logging to pyright pre-commit checks --------- Signed-off-by: Tim Gasser <[email protected]>
Description
Cleaned the logging/ directory and rebased on top of develop ready to merge.
Type-cleaning summary
This pull request introduces several fixes to address type errors discovered by
pyrightafter enabling it for thenemoguardrails/logging/directory. The changes enhance code robustness by handling potentialNonevalues and correcting type annotations.Medium Risk
Refactoring Class Inheritance
This change modifies the class structure and is classified as medium risk as it alters the method resolution order, though it's likely a safe cleanup of unused functionality.
nemoguardrails/logging/callbacks.py, Line 36StdOutCallbackHandlermay have been redundant or introduced conflicting method signatures.LoggingCallbackHandlerclass was simplified to only inherit fromAsyncCallbackHandler.StdOutCallbackHandlerfrom the base classes, the class hierarchy is simplified. This assumes that no functionality fromStdOutCallbackHandlerwas being used, and all logging behavior is self-contained. This is a clean way to remove unnecessary dependencies.Low Risk
These changes are considered low risk as they primarily involve adding defensive checks and correcting type hints, which prevent runtime errors without altering core logic.
1. Handling Potentially
NoneTimestampsnemoguardrails/logging/callbacks.py(Line 207),nemoguardrails/logging/processing_log.py(multiple lines)TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'. This error would occur when calculating durations withstarted_atorfinished_attimestamps that could beNone.Nonebefore calculating a duration. This prevents aTypeErrorat runtime. The implicit assumption is that if timestamps are missing, the duration can be safely defaulted to0.0.try...except TypeErrorblock is an option, but the explicitifcheck is clearer and more direct.2. Guarding Against
NoneObject Accessnemoguardrails/logging/processing_log.py, Lines 158, 169, 182, and others.AttributeError: 'NoneType' object has no attribute '...'. This would occur if objects likeactivated_railorexecuted_actionareNonewhen their attributes are accessed.Noneobjects is now wrapped in a null check.if activated_rail is not None:before using it, the code guards againstAttributeErrorexceptions. This is a standard defensive pattern for handling objects that may not be initialized in all code paths.ifcheck is the canonical and safest way to handle this in Python.3. Safe Aggregation of Optional Numeric Stats
nemoguardrails/logging/processing_log.py, Lines 261-276TypeError: unsupported operand type(s) for +=: 'NoneType' and 'int'. This arises when aggregating statistics where either the current total or the value to be added isNone.or 0pattern is used to provide a default value for optional numeric types during summation.or 0to coalesce anyNonevalues into0before the addition operation. This ensures the operation is always performed on numbers, preventing aTypeError. The assumption is thatNoneshould be treated as0for statistical sums.if/elseblock could achieve the same result, but the implemented solution is more concise and idiomatic.4. Correcting Exception Type Hints for Method Overriding
nemoguardrails/logging/callbacks.py, Lines 280, 311, 342Union[Exception, KeyboardInterrupt]) was not compatible with the superclass's expectedBaseException.errorparameter in error handlers was broadened toBaseException.BaseExceptionto correctly match the superclass signature inlangchain. This is the correct fix becauseKeyboardInterruptinherits fromBaseException, notException, makingBaseExceptionthe proper, compatible type for all possible exceptions.5. Resolving Type Invariance with
castnemoguardrails/logging/callbacks.py, Lines 383-394Argument "handlers" has incompatible type "List[LoggingCallbackHandler]"; expected "List[BaseCallbackHandler]". This is a classic variance issue where a list of a subclass is not assignable to a list of a superclass.typing.castis used to inform the type checker that the list of handlers is compatible.casttells the static type checker to treat thehandlerslist as aList[BaseCallbackHandler], resolving the type mismatch error without any runtime impact.handlers: List[BaseCallbackHandler] = [LoggingCallbackHandler()]. However, usingcastis a perfectly valid and direct way to fix this issue.Test Plan
Type-checking
$ poetry run pre-commit run --all-files check yaml...............................................................Passed fix end of files.........................................................Passed trim trailing whitespace.................................................Passed isort (python)...........................................................Passed black....................................................................Passed Insert license in comments...............................................Passed pyright..................................................................PassedUnit-tests
Local CLI check
Checklist