feat(smartpredictor): add structured logging on the shapash.smartpredictor logger - #742
Open
immu4989 wants to merge 1 commit into
Open
feat(smartpredictor): add structured logging on the shapash.smartpredictor logger#742immu4989 wants to merge 1 commit into
immu4989 wants to merge 1 commit into
Conversation
…ictor logger Implements Gap A of MAIF#734: structured logging at the SmartPredictor prediction boundary so production deployments can observe input shape, method timing, and error context, correlated to the deployed predictor version via the schema fingerprint from MAIF#722. - New module-level `logging.getLogger("shapash.smartpredictor")` logger. No new dependencies (stdlib only). Silent under Python's default logging config; users configure levels via standard `logging.config`. - `_instrument(operation)` decorator emits DEBUG on enter, INFO on successful exit with `elapsed_ms`, ERROR on unhandled exception (with `logger.exception` attaching the traceback). Every record carries the predictor's schema fingerprint in `extra={"schema_fingerprint": ...}` so downstream aggregators (Datadog / CloudWatch / OpenTelemetry) can correlate to the deployed version. - Applied to `add_input`, `predict_proba`, `predict`, `compute_contributions`, and `summarize`. `add_input` also emits an extra DEBUG record with the incoming `x`'s shape when provided. - `SmartPredictor._get_schema_fingerprint()` helper lazily caches the fingerprint on `_schema_fingerprint_cache`, backward compatible with pickles that predate the attribute (getattr with `None` fallback). Tests: 6 new tests in TestSmartPredictorLogging covering enter/completed records, extras (`elapsed_ms` + `schema_fingerprint`), the error path, `logging.disable(...)` silencing, the fingerprint cache behavior, and the default-config "no handlers attached" claim. Uses `unittest.TestCase.assertLogs` and `assertNoLogs` (Python 3.10+) — no new test dependencies. All 51 SmartPredictor + load_smartpredictor tests pass. Ruff format clean. Type hints on all new code per the convention established on MAIF#711 / MAIF#722. Refs MAIF#734 (Gap A of two; Gap B — schema-drift detection with in-pickle `schema_distribution` — will follow in a separate PR).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This PR implements Gap A of #734 — structured logging at the
SmartPredictorprediction boundary so production deployments can observe input shape, method timing, and error context, correlated to the deployed predictor version via the schema fingerprint introduced in #722.Gap B (schema-drift detection with an in-pickle
schema_distributionattribute, noskrubdependency, per @guillaume-vignal's decision on #734) will follow in a separate PR.What ships:
logging.getLogger("shapash.smartpredictor")logger. No new dependencies — stdlib only. Silent under Python's default logging config; users opt in via standardlogging.config._instrument(operation)decorator that emits:DEBUGon enter,INFOon successful exit withelapsed_ms,ERRORon unhandled exception (vialogger.exception, so the traceback is attached).extra={"schema_fingerprint": ..., "elapsed_ms": ...}so downstream aggregators (Datadog / CloudWatch / OpenTelemetry) can correlate log records to the deployed predictor version — matching the fingerprint written bysave()into the manifest sidecar (feat(smartpredictor): add version/schema manifest sidecar to save/load #722).add_input,predict_proba,predict,compute_contributions,summarize.add_inputalso emits an extraDEBUGrecord with the incomingx's shape.SmartPredictor._get_schema_fingerprint()lazily caches the fingerprint on_schema_fingerprint_cache. Backward compatible with pickles that predate the attribute (getattr(..., None)fallback).Sample log output with
logging.basicConfig(level=logging.INFO):Fixes #734 (Gap A only).
Type of change
How Has This Been Tested?
6 new tests in
TestSmartPredictorLoggingintests/unit_tests/explainer/test_smart_predictor.py:test_add_input_emits_enter_and_completed_records— confirms both boundary records land onshapash.smartpredictorwhenadd_inputis called.test_completed_records_include_elapsed_ms_and_fingerprint— assertsrecord.elapsed_msis a non-negative float andrecord.schema_fingerprintstarts with"sha256:"on every successful-exit record.test_error_path_emits_failed_record— feeds a malformedxto forcecheck_dataset_featuresto raise, then asserts at least oneERROR-level record with"add_input failed"message is emitted, still carryingelapsed_ms+schema_fingerprint.test_logging_disable_silences_records— callslogging.disable(CRITICAL)and usesTestCase.assertNoLogsto confirm nothing is emitted, so applications that opt out via the standard API stay silent.test_get_schema_fingerprint_caches— first call populates_schema_fingerprint_cache, second call returns the same cached value.test_default_logging_config_is_silent— confirms no handlers are attached toshapash.smartpredictorby default (guards against accidentally hard-coding stderr emission).Reproduce locally:
Test Configuration:
de85cfd)Other library versions: pandas 3.0.3, numpy 2.4.4, catboost 1.2.10, pytest 9.0.3.
Checklist:
_instrumentdecorator explains the emission contract, docstring on_get_schema_fingerprintexplains the lazy-cache and backward-compat behaviorNotes
shapash.smartpredictoras proposed in the issue — one logger, no sub-loggers. Happy to change to a different namespacing (e.g.shapash.smart_predictormatching the module path) if you'd prefer._schema_fingerprint_cacheattribute is populated on first_get_schema_fingerprint()call and persists across method calls. Pickles that predate this PR don't have the attribute; thegetattrfallback recomputes on first use. Assumes the schema attributes (features_dict,features_types,columns_dict,label_dict) aren't mutated after__init__— matches the current design intent.schema_distributionas a newSmartPredictorattribute (in-pickle, not sidecar), lightweight self-contained implementation, noskrubdependency. Will open once Gap A lands.