Skip to content

feat(governance): guardrail-fallback compensation#123

Open
aditik0303 wants to merge 1 commit into
feat/governance-auditfrom
feat/governance-guardrail-compensation
Open

feat(governance): guardrail-fallback compensation#123
aditik0303 wants to merge 1 commit into
feat/governance-auditfrom
feat/governance-guardrail-compensation

Conversation

@aditik0303

Copy link
Copy Markdown

Stacked PR 4/7 — part of splitting feat/governance-core into 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 onto feat/agentic-governance. feat/governance-core kept untouched as backup.

@aditik0303 aditik0303 requested a review from a team as a code owner June 12, 2026 11:45
@aditik0303 aditik0303 force-pushed the feat/governance-audit branch from 42e1f29 to 7111d27 Compare June 16, 2026 09:28
@aditik0303 aditik0303 force-pushed the feat/governance-guardrail-compensation branch from 8812695 to 2da1f67 Compare June 16, 2026 09:30
@aditik0303 aditik0303 force-pushed the feat/governance-audit branch from 7111d27 to 2db5f2d Compare June 17, 2026 06:35
@aditik0303 aditik0303 force-pushed the feat/governance-guardrail-compensation branch from 2da1f67 to 5b119ac Compare June 17, 2026 06:37
@aditik0303 aditik0303 force-pushed the feat/governance-audit branch from 2db5f2d to bd19932 Compare June 17, 2026 08:35
@aditik0303 aditik0303 force-pushed the feat/governance-guardrail-compensation branch from 5b119ac to 2154aba Compare June 17, 2026 08:35
@aditik0303 aditik0303 force-pushed the feat/governance-audit branch from bd19932 to add4e90 Compare June 19, 2026 08:08
@aditik0303 aditik0303 force-pushed the feat/governance-guardrail-compensation branch from 2154aba to 1f7bdad Compare June 19, 2026 08:08
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch from d500f99 to 7cdc791 Compare June 24, 2026 07:41
@viswa-uipath viswa-uipath force-pushed the feat/governance-guardrail-compensation branch from fb9756e to 0e9ad5b Compare June 24, 2026 08:13
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch from 7cdc791 to 4da27ce Compare June 24, 2026 09:55
@viswa-uipath viswa-uipath force-pushed the feat/governance-guardrail-compensation branch from 0e9ad5b to 470533e Compare June 24, 2026 10:57
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>
Comment thread src/uipath/runtime/governance/runtime.py Outdated
@viswa-uipath viswa-uipath requested a review from cristipufu June 26, 2026 11:08
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>
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch from 2f188d8 to 54a3fce Compare June 27, 2026 08:55
@viswa-uipath viswa-uipath force-pushed the feat/governance-guardrail-compensation branch from fc6cd33 to f183ad8 Compare June 27, 2026 09:29
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>
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch from fd61bc2 to d505d9d Compare June 27, 2026 10:26
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>
@viswa-uipath viswa-uipath force-pushed the feat/governance-guardrail-compensation branch 2 times, most recently from 9ba1072 to 5433054 Compare June 27, 2026 10:34
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch 2 times, most recently from 7955499 to 7e4ef8d Compare June 27, 2026 17:33
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>
@viswa-uipath viswa-uipath force-pushed the feat/governance-guardrail-compensation branch from 0b317f0 to 4dbff93 Compare June 27, 2026 19:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants