feat(governance): guardrail-fallback compensation#123
Open
aditik0303 wants to merge 1 commit into
Open
Conversation
42e1f29 to
7111d27
Compare
8812695 to
2da1f67
Compare
7111d27 to
2db5f2d
Compare
2da1f67 to
5b119ac
Compare
2db5f2d to
bd19932
Compare
5b119ac to
2154aba
Compare
bd19932 to
add4e90
Compare
2154aba to
1f7bdad
Compare
Merged
6 tasks
d500f99 to
7cdc791
Compare
fb9756e to
0e9ad5b
Compare
7cdc791 to
4da27ce
Compare
0e9ad5b to
470533e
Compare
viswa-uipath
added a commit
that referenced
this pull request
Jun 24, 2026
…orts Closes radu's recurring boundary objection for the evaluator slice and makes the post-rebase stack actually import. The evaluator was the last place where everything PR #121-#123 instance-scoped collapsed back to process globals. Architectural - GovernanceEvaluator gains constructor injection: GovernanceEvaluator(policy_index, *, enforcement_mode=AUDIT, audit_manager=None, compensator=None) - Drop get_audit_manager() / get_enforcement_mode() / submit_compensation free-function lookups. The evaluator now consults zero process-globals on the hot path. - mode property is read-only (drop the setter); no two-writer race between the loader and evaluator. - audit_manager=None and compensator=None short-circuit cleanly so tests + minimal wirings work without injecting every dep. - Drop unused is_enforce_mode() public method (dead code; no caller in src/ or tests/). Post-rebase plumbing - _dispatch_compensation uses self._compensator.submit(...) instead of the deleted free function; reads r.validator (Pydantic attribute) instead of the old r["validator"] TypedDict access. - _emit_audit passes policy_id (PR #122 trace-contract field, was rule_id) and enforcement_mode=mode enum (PR #122 required arg). - Import EnforcementMode from uipath.core.governance (governance.config deleted in PR #121); import AuditManager from _audit.base (audit/ is _audit/ post-PR-#122). native/__init__.py - Drop the four module-level loader-function re-exports (get_policy_index / load_policy_index / prefetch_policy_index / reset_policy_index) — all deleted in PR #121's PolicyLoader refactor. - Export PolicyLoader instead. Tests - test_evaluator: full rewrite. Drop deleted-import paths (tests._helpers.reset_enforcement_mode, governance.config). Replace the global-manager fixture with a per-test AuditManager that uses register_default_sinks=False + a capturing sink. Every GovernanceEvaluator() call routes through a _build_evaluator helper with explicit mode + manager. New test_no_audit_manager_short_circuits replaces the previous test that mocked the global to raise. - test_evaluator_operators: drop the autouse mode-isolating fixture (no globals to isolate); DISABLED-mode test passes enforcement_mode=EnforcementMode.DISABLED via constructor. - test_guardrail_compensation: rebase-conflict resolution dropped the stale incoming-side imports (Action/LifecycleHook, backend_client, unguarded GovernanceEvaluator) since none of them are referenced in the rest of the file. 357 passed, 1 skipped (pre-existing wrapper skip). Ruff clean. Mypy clean (11 source files). Bandit shows only the pre-existing B101 in _yaml_to_index.py (out of scope). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
viswa-uipath
added a commit
that referenced
this pull request
Jun 25, 2026
…Runtime Closes architecture-review §2.1 + §2.2 — the UiPathWrappedRuntimeFactory bolted governance onto the generic runtime-factory registry (apply_wrappers=True turned every registered factory into a different type, breaking isinstance checks), and the second GovernanceRuntime in governance/wrapper.py reached into delegate._agent_definition / framework-specific private attrs through a 10-level walk to install framework-blind callbacks. Both patterns the doc unambiguously says to delete. Composition belongs in the host's decorator chain, FF-gated, where UiPathResumableRuntime already wraps the framework runtime; this PR's wrapper machinery was an end-run around that. Deletions - src/uipath/runtime/governance/wrapper.py (1002 LOC) — the second GovernanceRuntime with _AGENT_ATTRS / _replace_agent_in_delegate / model-context-var introspection. - src/uipath/runtime/wrapper.py (55 LOC) — the lazy-import dispatch shim that called the deleted governance_wrapper. - tests/test_dispose_isolation.py, tests/test_wrapper.py, tests/test_wrapper_internals.py (~650 LOC combined) — entire test suites for the deleted modules. Updates - src/uipath/runtime/registry.py — UiPathWrappedRuntimeFactory class and the apply_wrappers kwarg removed from get(). The registry returns the registered factory unchanged; cross-cutting concerns (governance, audit, …) are composed by the host into the decorator chain, not auto-applied here. - src/uipath/runtime/__init__.py — drop GOVERNANCE_FEATURE_FLAG / apply_governance_wrapper exports. - tests/test_registry.py — strip every apply_wrappers=False kwarg (the kwarg is gone) and drop the wrapping-behaviour section + its fixtures. Conflict resolution The rebase onto #125's tip replayed the upstream e186f5f commit (a cosmetic helper-import touch) into three test files that my PR #122/#123/#124 refactors had already rewritten end-to-end. HEAD-side resolution kept the refactored form in test_evaluator.py, test_evaluator_operators.py, test_guardrail_compensation.py — the incoming side referenced symbols (governance.audit, governance.config, tests._helpers.reset_enforcement_mode) that the post-rebase stack no longer ships. Verification - Monorepo grep for UiPathWrappedRuntimeFactory, apply_wrappers, apply_governance_wrapper, governance_wrapper, and the deleted module import paths: zero hits. - ruff clean, mypy clean (45 source files), 357 passed + 1 skipped. Net diff on top of #125's tip: −2005 / +38 LOC = −1967 net. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
cristipufu
reviewed
Jun 26, 2026
viswa-uipath
added a commit
that referenced
this pull request
Jun 27, 2026
…orward Two reviewer comments + a stack-hygiene cleanup so the audit pipeline never introduces ``trace_id`` (which PR #123 then has to remove) and never names ``uipath-platform`` in docstrings. radu-mocanu line 75 — ``global _atexit_registered`` mutation - Wrap the three loose module-level names (``_live_managers``, ``_atexit_registered``, ``_atexit_lock``) plus the two helpers (``_process_cleanup_managers``, ``_register_manager_for_cleanup``) into a single ``_AuditManagerCleanupRegistry`` class. No more ``global`` mutation; cleanup state is named and swappable in tests. - Single module-level instance ``_cleanup_registry``; ``AuditManager.__init__`` calls ``_cleanup_registry.register(self)``. - Lifecycle tests reference ``audit_base._cleanup_registry.{live_managers, atexit_registered, process_cleanup}`` instead of the old globals. radu-mocanu line 105 — "shouldn't we have a parent span id as well?" - Solved without OTel-shaped fields on ``AuditEvent``. The audit manager queue now holds ``(contextvars.Context, AuditEvent)`` tuples; ``emit()`` captures ``contextvars.copy_context()`` on the caller thread (where the agent's OTel span is live) and the worker runs ``ctx.run(_emit_sync, event)``. - ``TracesAuditSink`` reads ``context.get_current()`` inside the captured snapshot — the agent's live span propagates across the worker hop and governance spans attach as children instead of orphan roots. Same pattern the guardrail compensator already uses. - Sentinel handling preserved (``None`` is still the shutdown marker); ``_drain_queue`` + drop-oldest backpressure all updated to the tuple shape. - New tests pin the propagation end-to-end: ``test_async_emit_propagates_caller_contextvars_to_worker_thread`` (real OTel ``TracerProvider`` + probe sink that asserts ``trace.get_current_span()`` on the worker matches the caller) and ``test_async_emit_drops_oldest_under_pressure_preserves_context`` (regression guard on the overflow branch). Pulled forward from PR #123 (so the stack tells a clean story) - ``AuditEvent.trace_id`` field never introduced (was about to be on this PR, then deleted on PR #123). ``emit_rule_evaluation`` / ``emit_hook_summary`` / ``emit_session_start`` / ``emit_session_end`` drop their ``trace_id`` kwargs. The two ``trace_id=session_id`` copy-paste bugs in the session emit helpers go away with the field. - ``TracesAuditSink`` drops the two ``span.set_attribute("uipath.trace_id", event.trace_id)`` calls. OTel SDK assigns the span's real trace id; UiPath exporter rebinds via ``UIPATH_TRACE_ID`` at export. - ``CheckContext.trace_id`` (in ``native/models.py``) dropped here too — no consumer on this branch (evaluator lives in PR #123+), safe and avoids PR #123 having to remove a field PR #122 added. Platform-reference scrub (also pulled forward from PR #123) - ``_audit/__init__.py`` + ``_audit/factory.py`` + ``_audit/base.py`` (3 sites): "platform-mandated" / "platform-owned" → "always-on" / "cannot be disabled by application code". - ``_audit/traces.py`` historical "previous version fabricated a random parent span_id" comment removed (radu-mocanu line 190); "(platform default = 2, Information)" comment renamed to "(Orchestrator default = 2, Information)" so it's not confused with the uipath-platform package. - ``tests/test_traces_severity.py`` matching renames; module docstring already generalized to "emitter" wording earlier in this branch. - ``tests/test_audit_manager_lifecycle.py`` propagation test renames dict keys ``captured["trace_id"]`` → ``captured["otel_trace_id"]`` (with a clarifying comment) so the dict labels can't be confused with an application-level trace id — the ``AuditEvent`` carries none. Lifecycle test updates from the field removals - ``test_traces_severity.py`` module docstring reflects "emitter stamps its own per-instance ``EnforcementMode``" (no "loader" or "evaluator" leakage, no "platform" wording). After this commit, ``grep -rn "trace_id\|platform\|UiPathPlatform" src tests`` on this branch returns zero substantive matches in the governance scope. The audit pipeline never introduces ``trace_id``, the cleanup registry has no ``global`` mutation, ``contextvars`` propagation pins the parent-span linkage without OTel-shaped fields on ``AuditEvent``, and no comment names ``uipath-platform``. Tests: ruff + mypy clean, 213 passed. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2f188d8 to
54a3fce
Compare
fc6cd33 to
f183ad8
Compare
viswa-uipath
added a commit
that referenced
this pull request
Jun 27, 2026
…orts Closes radu's recurring boundary objection for the evaluator slice and makes the post-rebase stack actually import. The evaluator was the last place where everything PR #121-#123 instance-scoped collapsed back to process globals. Architectural - GovernanceEvaluator gains constructor injection: GovernanceEvaluator(policy_index, *, enforcement_mode=AUDIT, audit_manager=None, compensator=None) - Drop get_audit_manager() / get_enforcement_mode() / submit_compensation free-function lookups. The evaluator now consults zero process-globals on the hot path. - mode property is read-only (drop the setter); no two-writer race between the loader and evaluator. - audit_manager=None and compensator=None short-circuit cleanly so tests + minimal wirings work without injecting every dep. - Drop unused is_enforce_mode() public method (dead code; no caller in src/ or tests/). Post-rebase plumbing - _dispatch_compensation uses self._compensator.submit(...) instead of the deleted free function; reads r.validator (Pydantic attribute) instead of the old r["validator"] TypedDict access. - _emit_audit passes policy_id (PR #122 trace-contract field, was rule_id) and enforcement_mode=mode enum (PR #122 required arg). - Import EnforcementMode from uipath.core.governance (governance.config deleted in PR #121); import AuditManager from _audit.base (audit/ is _audit/ post-PR-#122). native/__init__.py - Drop the four module-level loader-function re-exports (get_policy_index / load_policy_index / prefetch_policy_index / reset_policy_index) — all deleted in PR #121's PolicyLoader refactor. - Export PolicyLoader instead. Tests - test_evaluator: full rewrite. Drop deleted-import paths (tests._helpers.reset_enforcement_mode, governance.config). Replace the global-manager fixture with a per-test AuditManager that uses register_default_sinks=False + a capturing sink. Every GovernanceEvaluator() call routes through a _build_evaluator helper with explicit mode + manager. New test_no_audit_manager_short_circuits replaces the previous test that mocked the global to raise. - test_evaluator_operators: drop the autouse mode-isolating fixture (no globals to isolate); DISABLED-mode test passes enforcement_mode=EnforcementMode.DISABLED via constructor. - test_guardrail_compensation: rebase-conflict resolution dropped the stale incoming-side imports (Action/LifecycleHook, backend_client, unguarded GovernanceEvaluator) since none of them are referenced in the rest of the file. 357 passed, 1 skipped (pre-existing wrapper skip). Ruff clean. Mypy clean (11 source files). Bandit shows only the pre-existing B101 in _yaml_to_index.py (out of scope). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
fd61bc2 to
d505d9d
Compare
viswa-uipath
added a commit
that referenced
this pull request
Jun 27, 2026
…orts Closes radu's recurring boundary objection for the evaluator slice and makes the post-rebase stack actually import. The evaluator was the last place where everything PR #121-#123 instance-scoped collapsed back to process globals. Architectural - GovernanceEvaluator gains constructor injection: GovernanceEvaluator(policy_index, *, enforcement_mode=AUDIT, audit_manager=None, compensator=None) - Drop get_audit_manager() / get_enforcement_mode() / submit_compensation free-function lookups. The evaluator now consults zero process-globals on the hot path. - mode property is read-only (drop the setter); no two-writer race between the loader and evaluator. - audit_manager=None and compensator=None short-circuit cleanly so tests + minimal wirings work without injecting every dep. - Drop unused is_enforce_mode() public method (dead code; no caller in src/ or tests/). Post-rebase plumbing - _dispatch_compensation uses self._compensator.submit(...) instead of the deleted free function; reads r.validator (Pydantic attribute) instead of the old r["validator"] TypedDict access. - _emit_audit passes policy_id (PR #122 trace-contract field, was rule_id) and enforcement_mode=mode enum (PR #122 required arg). - Import EnforcementMode from uipath.core.governance (governance.config deleted in PR #121); import AuditManager from _audit.base (audit/ is _audit/ post-PR-#122). native/__init__.py - Drop the four module-level loader-function re-exports (get_policy_index / load_policy_index / prefetch_policy_index / reset_policy_index) — all deleted in PR #121's PolicyLoader refactor. - Export PolicyLoader instead. Tests - test_evaluator: full rewrite. Drop deleted-import paths (tests._helpers.reset_enforcement_mode, governance.config). Replace the global-manager fixture with a per-test AuditManager that uses register_default_sinks=False + a capturing sink. Every GovernanceEvaluator() call routes through a _build_evaluator helper with explicit mode + manager. New test_no_audit_manager_short_circuits replaces the previous test that mocked the global to raise. - test_evaluator_operators: drop the autouse mode-isolating fixture (no globals to isolate); DISABLED-mode test passes enforcement_mode=EnforcementMode.DISABLED via constructor. - test_guardrail_compensation: rebase-conflict resolution dropped the stale incoming-side imports (Action/LifecycleHook, backend_client, unguarded GovernanceEvaluator) since none of them are referenced in the rest of the file. 357 passed, 1 skipped (pre-existing wrapper skip). Ruff clean. Mypy clean (11 source files). Bandit shows only the pre-existing B101 in _yaml_to_index.py (out of scope). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
9ba1072 to
5433054
Compare
7955499 to
7e4ef8d
Compare
Rebase of the guardrail-compensation series onto feat/governance-audit's
tip. Brings up the native governance layer in one squash:
- In-runtime policy evaluator (native/evaluator.py): rule + check +
condition matching with VADER sentiment / chardet / regex / entropy
/ incident / commitment operators. Honors per-check action overrides
and cross-rule aggregation. Instance-scoped with explicit deps
(AuditManager + GuardrailCompensator) injected by the host.
- Native package exports (native/__init__.py): build_policy_index_from_yaml
+ GovernanceEvaluator + GuardrailCompensator + CheckContext + PolicyIndex.
- GuardrailCompensator (native/guardrail_compensation.py): bounded
ThreadPoolExecutor + BoundedSemaphore per runtime, contextvars
propagation, weakref-tracked process-level atexit. Delegates HTTP /
auth / URL / trace correlation to the injected
GovernanceCompensationProvider.
- Drop PolicyLoader: host fetches policy asynchronously via
GovernancePolicyProvider and hands the resolved PolicyIndex to
UiPathGovernedRuntime at construction.
- Trace correlation: AuditEvent / AuditRecord no longer carry trace_id;
OTel-backed sinks resolve from the live span via the
AuditManager's captured contextvars snapshot.
- testpypi dev pin (pyproject.toml): uipath-core
0.5.24.dev1017610000..0.5.24.dev1017620000 from PR
UiPath/uipath-python#1761 (AdapterRegistry deletion +
AuditRecord.trace_id field drop).
Tests: 346 passed + 1 skipped, ruff + mypy clean.
Pre-rebase tip preserved at backup-guardrail-pre-audit-rebase-2026-06-28
for reference.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
0b317f0 to
4dbff93
Compare
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.
Stacked PR 4/7 — part of splitting
feat/governance-coreinto reviewable slices. Base:feat/governance-audit. One logical slice (branch is cumulative so CI is green). Merge in order #1 → #7 and delete each branch on merge so the next PR auto-retargets ontofeat/agentic-governance.feat/governance-corekept untouched as backup.