Repository navigation
FEAT: Add session audit context API (set_audit_context / get_audit_context) - #622
Kaps (kapilsamant) wants to merge 8 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds a session metadata/auditing API on the SQL Server connection using sp_set_session_context, plus a test suite to validate local caching, server round-trips, and error conditions.
Changes:
- Implement
Connection.set_audit_context()to set/merge/clear session context keys and maintain a local cache. - Implement
Connection.get_audit_context()to expose the cached context safely (copy). - Add pytest coverage for server round-trip behavior, merging, clearing, read-only keys, closed-connection errors, and size/type validation.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| tests/test_023_audit_context.py | New tests covering the new audit context API behaviors and error cases. |
| mssql_python/connection.py | Adds set_audit_context/get_audit_context APIs backed by sp_set_session_context with validation and caching. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
|
/azp run |
|
Azure Pipelines successfully started running 1 pipeline(s). |
|
Kaps (@kapilsamant) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.
Contributor License AgreementContribution License AgreementThis Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
|
PR Performance ReportPerformance could not be assessed. No matching performance run appeared within the 220-minute wait for |
There was a problem hiding this comment.
🟡 Changes recommended
Four bare generic annotations fail the blocking strict-mypy gate, while unresolved Unicode validation and explicit session-context clearing bugs also affect correctness.
6 open issues
Use concrete generic types to pass strict mypy checks · New Add session-context methods to the shipped type stub · New Measure key and value limits in encoded UTF-16 units · New Clear explicitly requested keys even when untracked · New Avoid redundant SQL cleanup on pooled connection close · New Test session isolation using real pooled connections · New
5 resolved since last review
The test currently acceptsTypeError, butset_audit_contextexplicitly converts non-string…_AUDIT_VALUE_MAX_LENbeing8000characters is likely incorrect for Pythonstrvalues, which… The docstring saysProgrammingErroris raised when a key/value “contains invalid characters”, but… These appear to be trailing whitespace/blank lines introduced in the diff. Please remove them to… These appear to be trailing whitespace/blank lines introduced in the diff. Please remove them to…
Review effort: Balanced
| if not hasattr(self, "_session_context"): | ||
| self._session_context: Dict[str, str] = {} | ||
| if not hasattr(self, "_session_context_read_only_keys"): | ||
| self._session_context_read_only_keys: set = set() |
| _SESSION_KEY_MAX_LEN: int = 128 | ||
| _SESSION_VALUE_MAX_LEN: int = 4000 | ||
|
|
||
| def set_session_context( |
| if len(key) > self._SESSION_KEY_MAX_LEN: | ||
| raise ProgrammingError( | ||
| driver_error="Session context key too long", | ||
| ddbc_error=( | ||
| f"Session context key exceeds {self._SESSION_KEY_MAX_LEN} characters" | ||
| ), | ||
| ) | ||
| if value is not None: | ||
| if not isinstance(value, str): | ||
| raise ProgrammingError( | ||
| driver_error="Invalid session context value", | ||
| ddbc_error="Session context values must be strings or None", | ||
| ) | ||
| if len(value) > self._SESSION_VALUE_MAX_LEN: | ||
| raise ProgrammingError( | ||
| driver_error="Session context value too long", | ||
| ddbc_error=( | ||
| f"Session context value exceeds {self._SESSION_VALUE_MAX_LEN} characters" | ||
| ), | ||
| ) |
| if not hasattr(self, "_session_context") or not self._session_context: | ||
| return | ||
|
|
||
| read_only_keys: set = getattr(self, "_session_context_read_only_keys", set()) | ||
|
|
||
| if keys: | ||
| # Validate that none of the requested keys are read-only. | ||
| read_only_requested = read_only_keys & set(keys) | ||
| if read_only_requested: | ||
| raise ProgrammingError( | ||
| driver_error="Cannot clear read-only session context keys", | ||
| ddbc_error=( | ||
| "The following keys are read-only and cannot be cleared: " | ||
| + ", ".join(sorted(read_only_requested)) | ||
| ), | ||
| ) | ||
| to_clear = [k for k in keys if k in self._session_context] |
| # If pooling is enabled, clear session context so the next consumer | ||
| # of this ODBC handle does not inherit leftover metadata. | ||
| if self._pooling and hasattr(self, "_session_context") and self._session_context: | ||
| read_only_keys = getattr(self, "_session_context_read_only_keys", set()) | ||
| if read_only_keys & set(self._session_context): | ||
| logger.warning( | ||
| "Pooled connection has read-only session context keys that " | ||
| "cannot be cleared: %s. These values will persist for the " | ||
| "next consumer of this connection.", | ||
| ", ".join(sorted(read_only_keys & set(self._session_context))), | ||
| ) | ||
| try: | ||
| self.clear_session_context() | ||
| except Exception: | ||
| logger.warning( | ||
| "Failed to clear session context before pool return", | ||
| exc_info=True, | ||
| ) |
| conn._pooling = True | ||
| conn.close() | ||
| # After close the cache should be empty | ||
| assert not getattr(conn, "_session_context", {}) |



Work Item / Issue Reference
Summary
Add session-level auditing/tracing API to the Connection class via two new methods:
set_audit_context() -> Sets session metadata (application, module, action, user_id, and arbitrary extra keys) on the current connection using sp_set_session_context. Supports read_only mode, input validation with length limits, parameterized query execution, and local caching of set values.
get_audit_context()-> Returns a copy of the locally cached session context dictionary.
Values set through this API are visible to SESSION_CONTEXT() in T-SQL, Extended Events, sys.dm_exec_sessions, and audit specifications.