Skip to content

feat(governance): audit pipeline — manager, console + traces sinks#122

Open
aditik0303 wants to merge 1 commit into
feat/governance-foundationfrom
feat/governance-audit
Open

feat(governance): audit pipeline — manager, console + traces sinks#122
aditik0303 wants to merge 1 commit into
feat/governance-foundationfrom
feat/governance-audit

Conversation

@aditik0303

Copy link
Copy Markdown

Stacked PR 3/7 — part of splitting feat/governance-core into reviewable slices. Base: feat/governance-policy-loading. 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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a governance audit pipeline with pluggable sinks, introducing OpenTelemetry trace spans for Orchestrator Traces and a developer-oriented console sink, plus tests that pin expected filtering and severity/status semantics.

Changes:

  • Introduces AuditManager + AuditSink framework with async queueing, circuit-breaker behavior, and default sink configuration.
  • Adds built-in sinks: TracesAuditSink (OTel spans) and ConsoleAuditSink (stderr output), plus a simple sink factory.
  • Adds tests covering console formatting/filtering, sink re-registration counter reset semantics, and trace severity/status behavior.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/test_traces_severity.py Verifies span verbosityLevel and error-status semantics for rule vs hook spans across enforcement modes.
tests/test_audit_register_sink.py Tests AuditManager.register_sink behavior around circuit-breaker counters and duplicate registration.
tests/test_audit_console.py Tests ConsoleAuditSink filtering and per-event formatting to stderr.
src/uipath/runtime/governance/audit/traces.py Implements OpenTelemetry span emission for hook summaries and rule evaluations.
src/uipath/runtime/governance/audit/factory.py Adds a name-based sink factory (traces, console) with env-driven console verbosity.
src/uipath/runtime/governance/audit/console.py Implements stderr console sink with verbose/non-verbose filtering.
src/uipath/runtime/governance/audit/base.py Adds core audit model, sink base class, and AuditManager with async worker/queue + circuit-breaker.
src/uipath/runtime/governance/audit/init.py Exposes audit framework public API and documents built-in sinks and env vars.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/uipath/runtime/governance/audit/base.py
Comment thread src/uipath/runtime/governance/audit/base.py
Comment thread src/uipath/runtime/governance/audit/traces.py Outdated
Comment thread tests/test_traces_severity.py Outdated
@aditik0303 aditik0303 force-pushed the feat/governance-policy-loading branch from 91309f8 to 418fd8f Compare June 16, 2026 09:07
@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-policy-loading branch from 418fd8f to 14bd3cc Compare June 17, 2026 05:27
@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-policy-loading branch from 14bd3cc to acfa5b5 Compare June 17, 2026 08:34
@aditik0303 aditik0303 force-pushed the feat/governance-audit branch 2 times, most recently from bd19932 to add4e90 Compare June 19, 2026 08:08
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch 2 times, most recently from 7cdc791 to 4da27ce Compare June 24, 2026 09:55
viswa-uipath added a commit that referenced this pull request Jun 24, 2026
…from wiring

Addresses radu's recurring PR #121 patterns applied to the guardrail
compensation slice. Resolves the post-PR-#121 ImportError in the test
file (it referenced the deleted ``uipath.runtime.governance.config`` /
``tests._helpers.reset_enforcement_mode``).

Architectural — match the AuditManager / PolicyLoader shape
- New GuardrailCompensator class. Each GovernanceRuntime instance gets
  one — owns its own ThreadPoolExecutor, BoundedSemaphore, and provider.
  uipath eval parallel runtimes no longer share workers, queue slots,
  or saturation state.
- Module globals _pool / _inflight / _INFLIGHT_CAP / @atexit.register
  decorator removed. Process cleanup via a weakref.WeakSet of live
  compensators + one process-level atexit hook (same pattern PR #122
  introduced for AuditManager): N runtimes → 1 atexit slot, no strong
  ref pinning disposed compensators.
- close() is an instance method, idempotent, logs at debug on failure.
- The free submit_compensation function is gone — callers use
  compensator.submit(...).

Boundary — env reads move to the wiring layer
- _resolve_trace_id signature changed to (supplied, fallback). It no
  longer reads UIPATH_TRACE_ID. The runtime layer is now env-free for
  this code path.
- GovernanceRuntime accepts a trace_id: str | None constructor arg and
  exposes it via the .trace_id property. The wiring layer (uipath CLI)
  reads UIPATH_TRACE_ID and passes the value in; the evaluator slice
  forwards it into GuardrailCompensator(provider, trace_id=...).
- GuardrailCompensator accepts trace_id at construction; it becomes
  the authoritative source. Per-submit trace_id is a per-call fallback.

Polish
- Replaced bare except Exception: pass in _resolve_trace_id with a
  logger.debug (bandit B110 cleared on this file).
- Removed ENV_TRACE_ID constant + the os import that backed it.

Tests
- Full rewrite of test_guardrail_compensation to drop deleted imports
  (config, reset_enforcement_mode), use GuardrailCompensator(provider),
  and mirror AuditManager's lifecycle test set (one atexit
  registration, weakref GC, idempotent close, cross-instance
  isolation, semaphore release on provider error).
- New test_resolve_trace_id_does_not_read_env pins the boundary rule:
  even with UIPATH_TRACE_ID set, the runtime layer ignores it.
- New test_compensator_trace_id_overrides_caller_supplied_value pins
  the construction-supplied value winning over per-submit.
- New test_governance_runtime_stashes_trace_id +
  test_governance_runtime_default_trace_id_is_none cover the new
  GovernanceRuntime kwarg + property.

238 passed, ruff/mypy clean; bandit clean on the touched files (one
pre-existing B101 in _yaml_to_index.py is unchanged and 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 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/_audit/traces.py Outdated
Comment thread src/uipath/runtime/governance/_audit/base.py Outdated
viswa-uipath added a commit that referenced this pull request Jun 26, 2026
…ents

Two of the comments in this PR described how the implementation USED
to behave (per-instance atexit hooks, fabricated remote-parent
span_ids) rather than what it does now. Reviewer flagged both and
asked for them to be removed.

While in here, generalized a handful of doc strings that referenced
specific upstream/downstream names (``PolicyLoader``, "evaluator")
inside this module's docs. The audit module shouldn't be coupled to
those names — what it actually relies on is "the emitter passes its
own per-instance EnforcementMode on each event". Generalizing reads
the same on this branch and stays correct as the stack lands.

Reviewer-flagged
- ``_audit/base.py`` module-level comment block: dropped the
  "per-instance atexit hook held the manager alive until process
  exit" historical aside; kept the forward-looking statement of what
  the WeakSet enables.
- ``_audit/traces.py`` ``_emit_hook_span``: dropped the "A previous
  version fabricated a random parent span_id…" paragraph; kept the
  current-behavior description.

Consistency mirrors
- ``_audit/traces.py`` ``_emit_rule_span`` cross-referenced the
  removed paragraph ("rely on the current OTel context rather than
  fabricating a remote-parent span_id"); cleaned up to match.

Generalizations
- ``_audit/base.py`` ``emit_rule_evaluation`` / ``emit_session_start``
  docstrings: ``"per-loader mode"`` / ``"instance-scoped loaders"``
  → ``"emitter's per-instance mode"`` / ``"each emitter
  (instance-scoped)"``.
- ``_audit/traces.py`` ``_resolve_mode`` docstring +
  ``_emit_hook_span`` / ``_emit_rule_span`` inline comments:
  ``"loader's per-instance mode"`` / ``"evaluator stamps it from the
  per-loader instance"`` / ``"per-loader instance"`` → variants of
  ``"each emitter stamps its own per-instance mode"``.
- ``tests/test_traces_severity.py`` module docstring: explicit
  ``PolicyLoader.enforcement_mode`` reference → generic
  ``EnforcementMode``.

ruff + mypy clean (8 source files). 211 passed. No behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Comment thread src/uipath/runtime/governance/_audit/base.py Outdated
Comment thread src/uipath/runtime/governance/_audit/base.py Outdated
viswa-uipath added a commit that referenced this pull request Jun 27, 2026
…rm refs

Trace correlation is owned by the wire-side governance service; the
runtime layer holds nothing about trace ids. This commit completes the
removal across every site that still carried the concept and scrubs
docstrings/comments that named the platform package directly.

Trace-id removal (hard delete)
- ``CheckContext.trace_id`` field dropped (``native/models.py``).
- ``AuditEvent.trace_id`` field dropped (``_audit/base.py``).
- ``GovernanceEvaluator.evaluate_*`` — all six methods drop the
  ``trace_id`` kwarg; ``CheckContext(...)`` ctors stop passing it.
- ``AuditRecord(...)`` ctors in the evaluator (DISABLED short-circuit
  + main path) drop ``trace_id=context.trace_id``.
- ``AuditManager.emit_rule_evaluation`` / ``emit_hook_summary`` /
  ``emit_session_start`` / ``emit_session_end`` drop their
  ``trace_id`` kwargs. Side effect: the two ``trace_id=session_id``
  copy-paste bugs in the session emit helpers are deleted along with
  the field.
- ``TracesAuditSink`` drops the two
  ``span.set_attribute("uipath.trace_id", event.trace_id)`` calls.
  The OTel SDK assigns the span's real trace id; the uipath OTel
  exporter handles wire-level correlation.

Platform-reference scrub
- ``native/guardrail_compensation.py`` module docstring + ``__init__``
  docstring drop the explicit
  ``uipath.platform.governance.UiPathPlatformGovernanceProvider``
  mention; replaced with neutral "concrete provider" language.
- ``submit()`` docstring no longer names ``resolve_trace_id`` — describes
  contextvars propagation generically.
- ``native/_yaml_to_index.py`` module docstring drops "platform host" →
  "host".
- ``native/models.py`` ``CheckContext`` docstring drops "platform
  boundary" → "wire-side provider at HTTP-call time".
- ``runtime.py`` module docstring drops "platform host" / "platform-side
  governance service" → "host CLI" / "injected provider".
- ``_audit/base.py`` ``AuditEvent`` docstring stops naming
  ``resolve_trace_id``; ``AuditManager`` + ``_register_traces_sink`` +
  ctor docstrings replace "platform-mandated" / "platform-owned" with
  "always-on" / "registered for every manager and cannot be disabled
  by application code".
- ``_audit/factory.py`` + ``_audit/__init__.py`` drop "platform-mandated"
  / "platform-owned".
- ``_audit/traces.py`` historical "previous version fabricated a random
  parent span_id" comment removed (PR #122 reviewer pattern); the
  "(platform default = 2, Information)" verbosityLevel comment
  renamed to "Orchestrator default" so it's not confused with the
  uipath-platform package.
- Tests: ``test_governance_runtime`` / ``test_guardrail_compensation`` /
  ``test_traces_severity`` rephrase every "platform-side" / "platform
  resolves" / "uipath-platform's own tests" mention to neutral
  provider-side wording.

Test updates from the dataclass-field removals
- ``test_evaluator.py`` ``_ctx`` helper drops ``trace_id``.
- ``test_evaluator_operators.py`` ``_ctx`` helper, the
  ``_record_context_evaluator`` ``AuditRecord`` ctor, and the six
  ``evaluate_*`` call sites drop ``trace_id``.

After this commit, ``grep -rn "platform\|UiPathPlatform\|resolve_trace_id"
src/uipath/runtime/governance tests`` returns zero matches. The runtime
layer reads as a generic governance runtime that takes an injected
``GovernanceCompensationProvider`` and doesn't name any specific
implementation or upstream package.

Depends on ``cb498cee`` in uipath-python (``EvaluatorProtocol`` +
``AuditRecord`` field drop).

Tests: ruff + mypy clean, 319 passed + 1 skipped (pre-existing
wrapper-not-present skip).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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 changed the base branch from feat/governance-policy-loading to feat/governance-foundation June 27, 2026 09:19
@viswa-uipath viswa-uipath requested a review from radu-mocanu June 27, 2026 09:22
viswa-uipath added a commit that referenced this pull request Jun 27, 2026
…from wiring

Addresses radu's recurring PR #121 patterns applied to the guardrail
compensation slice. Resolves the post-PR-#121 ImportError in the test
file (it referenced the deleted ``uipath.runtime.governance.config`` /
``tests._helpers.reset_enforcement_mode``).

Architectural — match the AuditManager / PolicyLoader shape
- New GuardrailCompensator class. Each GovernanceRuntime instance gets
  one — owns its own ThreadPoolExecutor, BoundedSemaphore, and provider.
  uipath eval parallel runtimes no longer share workers, queue slots,
  or saturation state.
- Module globals _pool / _inflight / _INFLIGHT_CAP / @atexit.register
  decorator removed. Process cleanup via a weakref.WeakSet of live
  compensators + one process-level atexit hook (same pattern PR #122
  introduced for AuditManager): N runtimes → 1 atexit slot, no strong
  ref pinning disposed compensators.
- close() is an instance method, idempotent, logs at debug on failure.
- The free submit_compensation function is gone — callers use
  compensator.submit(...).

Boundary — env reads move to the wiring layer
- _resolve_trace_id signature changed to (supplied, fallback). It no
  longer reads UIPATH_TRACE_ID. The runtime layer is now env-free for
  this code path.
- GovernanceRuntime accepts a trace_id: str | None constructor arg and
  exposes it via the .trace_id property. The wiring layer (uipath CLI)
  reads UIPATH_TRACE_ID and passes the value in; the evaluator slice
  forwards it into GuardrailCompensator(provider, trace_id=...).
- GuardrailCompensator accepts trace_id at construction; it becomes
  the authoritative source. Per-submit trace_id is a per-call fallback.

Polish
- Replaced bare except Exception: pass in _resolve_trace_id with a
  logger.debug (bandit B110 cleared on this file).
- Removed ENV_TRACE_ID constant + the os import that backed it.

Tests
- Full rewrite of test_guardrail_compensation to drop deleted imports
  (config, reset_enforcement_mode), use GuardrailCompensator(provider),
  and mirror AuditManager's lifecycle test set (one atexit
  registration, weakref GC, idempotent close, cross-instance
  isolation, semaphore release on provider error).
- New test_resolve_trace_id_does_not_read_env pins the boundary rule:
  even with UIPATH_TRACE_ID set, the runtime layer ignores it.
- New test_compensator_trace_id_overrides_caller_supplied_value pins
  the construction-supplied value winning over per-submit.
- New test_governance_runtime_stashes_trace_id +
  test_governance_runtime_default_trace_id_is_none cover the new
  GovernanceRuntime kwarg + property.

238 passed, ruff/mypy clean; bandit clean on the touched files (one
pre-existing B101 in _yaml_to_index.py is unchanged and 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 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 added a commit that referenced this pull request Jun 27, 2026
…rm refs

Trace correlation is owned by the wire-side governance service; the
runtime layer holds nothing about trace ids. This commit completes the
removal across every site that still carried the concept and scrubs
docstrings/comments that named the platform package directly.

Trace-id removal (hard delete)
- ``CheckContext.trace_id`` field dropped (``native/models.py``).
- ``AuditEvent.trace_id`` field dropped (``_audit/base.py``).
- ``GovernanceEvaluator.evaluate_*`` — all six methods drop the
  ``trace_id`` kwarg; ``CheckContext(...)`` ctors stop passing it.
- ``AuditRecord(...)`` ctors in the evaluator (DISABLED short-circuit
  + main path) drop ``trace_id=context.trace_id``.
- ``AuditManager.emit_rule_evaluation`` / ``emit_hook_summary`` /
  ``emit_session_start`` / ``emit_session_end`` drop their
  ``trace_id`` kwargs. Side effect: the two ``trace_id=session_id``
  copy-paste bugs in the session emit helpers are deleted along with
  the field.
- ``TracesAuditSink`` drops the two
  ``span.set_attribute("uipath.trace_id", event.trace_id)`` calls.
  The OTel SDK assigns the span's real trace id; the uipath OTel
  exporter handles wire-level correlation.

Platform-reference scrub
- ``native/guardrail_compensation.py`` module docstring + ``__init__``
  docstring drop the explicit
  ``uipath.platform.governance.UiPathPlatformGovernanceProvider``
  mention; replaced with neutral "concrete provider" language.
- ``submit()`` docstring no longer names ``resolve_trace_id`` — describes
  contextvars propagation generically.
- ``native/_yaml_to_index.py`` module docstring drops "platform host" →
  "host".
- ``native/models.py`` ``CheckContext`` docstring drops "platform
  boundary" → "wire-side provider at HTTP-call time".
- ``runtime.py`` module docstring drops "platform host" / "platform-side
  governance service" → "host CLI" / "injected provider".
- ``_audit/base.py`` ``AuditEvent`` docstring stops naming
  ``resolve_trace_id``; ``AuditManager`` + ``_register_traces_sink`` +
  ctor docstrings replace "platform-mandated" / "platform-owned" with
  "always-on" / "registered for every manager and cannot be disabled
  by application code".
- ``_audit/factory.py`` + ``_audit/__init__.py`` drop "platform-mandated"
  / "platform-owned".
- ``_audit/traces.py`` historical "previous version fabricated a random
  parent span_id" comment removed (PR #122 reviewer pattern); the
  "(platform default = 2, Information)" verbosityLevel comment
  renamed to "Orchestrator default" so it's not confused with the
  uipath-platform package.
- Tests: ``test_governance_runtime`` / ``test_guardrail_compensation`` /
  ``test_traces_severity`` rephrase every "platform-side" / "platform
  resolves" / "uipath-platform's own tests" mention to neutral
  provider-side wording.

Test updates from the dataclass-field removals
- ``test_evaluator.py`` ``_ctx`` helper drops ``trace_id``.
- ``test_evaluator_operators.py`` ``_ctx`` helper, the
  ``_record_context_evaluator`` ``AuditRecord`` ctor, and the six
  ``evaluate_*`` call sites drop ``trace_id``.

After this commit, ``grep -rn "platform\|UiPathPlatform\|resolve_trace_id"
src/uipath/runtime/governance tests`` returns zero matches. The runtime
layer reads as a generic governance runtime that takes an injected
``GovernanceCompensationProvider`` and doesn't name any specific
implementation or upstream package.

Depends on ``cb498cee`` in uipath-python (``EvaluatorProtocol`` +
``AuditRecord`` field drop).

Tests: ruff + mypy clean, 319 passed + 1 skipped (pre-existing
wrapper-not-present skip).

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
…from wiring

Addresses radu's recurring PR #121 patterns applied to the guardrail
compensation slice. Resolves the post-PR-#121 ImportError in the test
file (it referenced the deleted ``uipath.runtime.governance.config`` /
``tests._helpers.reset_enforcement_mode``).

Architectural — match the AuditManager / PolicyLoader shape
- New GuardrailCompensator class. Each GovernanceRuntime instance gets
  one — owns its own ThreadPoolExecutor, BoundedSemaphore, and provider.
  uipath eval parallel runtimes no longer share workers, queue slots,
  or saturation state.
- Module globals _pool / _inflight / _INFLIGHT_CAP / @atexit.register
  decorator removed. Process cleanup via a weakref.WeakSet of live
  compensators + one process-level atexit hook (same pattern PR #122
  introduced for AuditManager): N runtimes → 1 atexit slot, no strong
  ref pinning disposed compensators.
- close() is an instance method, idempotent, logs at debug on failure.
- The free submit_compensation function is gone — callers use
  compensator.submit(...).

Boundary — env reads move to the wiring layer
- _resolve_trace_id signature changed to (supplied, fallback). It no
  longer reads UIPATH_TRACE_ID. The runtime layer is now env-free for
  this code path.
- GovernanceRuntime accepts a trace_id: str | None constructor arg and
  exposes it via the .trace_id property. The wiring layer (uipath CLI)
  reads UIPATH_TRACE_ID and passes the value in; the evaluator slice
  forwards it into GuardrailCompensator(provider, trace_id=...).
- GuardrailCompensator accepts trace_id at construction; it becomes
  the authoritative source. Per-submit trace_id is a per-call fallback.

Polish
- Replaced bare except Exception: pass in _resolve_trace_id with a
  logger.debug (bandit B110 cleared on this file).
- Removed ENV_TRACE_ID constant + the os import that backed it.

Tests
- Full rewrite of test_guardrail_compensation to drop deleted imports
  (config, reset_enforcement_mode), use GuardrailCompensator(provider),
  and mirror AuditManager's lifecycle test set (one atexit
  registration, weakref GC, idempotent close, cross-instance
  isolation, semaphore release on provider error).
- New test_resolve_trace_id_does_not_read_env pins the boundary rule:
  even with UIPATH_TRACE_ID set, the runtime layer ignores it.
- New test_compensator_trace_id_overrides_caller_supplied_value pins
  the construction-supplied value winning over per-submit.
- New test_governance_runtime_stashes_trace_id +
  test_governance_runtime_default_trace_id_is_none cover the new
  GovernanceRuntime kwarg + property.

238 passed, ruff/mypy clean; bandit clean on the touched files (one
pre-existing B101 in _yaml_to_index.py is unchanged and 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 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 added a commit that referenced this pull request Jun 27, 2026
…rm refs

Trace correlation is owned by the wire-side governance service; the
runtime layer holds nothing about trace ids. This commit completes the
removal across every site that still carried the concept and scrubs
docstrings/comments that named the platform package directly.

Trace-id removal (hard delete)
- ``CheckContext.trace_id`` field dropped (``native/models.py``).
- ``AuditEvent.trace_id`` field dropped (``_audit/base.py``).
- ``GovernanceEvaluator.evaluate_*`` — all six methods drop the
  ``trace_id`` kwarg; ``CheckContext(...)`` ctors stop passing it.
- ``AuditRecord(...)`` ctors in the evaluator (DISABLED short-circuit
  + main path) drop ``trace_id=context.trace_id``.
- ``AuditManager.emit_rule_evaluation`` / ``emit_hook_summary`` /
  ``emit_session_start`` / ``emit_session_end`` drop their
  ``trace_id`` kwargs. Side effect: the two ``trace_id=session_id``
  copy-paste bugs in the session emit helpers are deleted along with
  the field.
- ``TracesAuditSink`` drops the two
  ``span.set_attribute("uipath.trace_id", event.trace_id)`` calls.
  The OTel SDK assigns the span's real trace id; the uipath OTel
  exporter handles wire-level correlation.

Platform-reference scrub
- ``native/guardrail_compensation.py`` module docstring + ``__init__``
  docstring drop the explicit
  ``uipath.platform.governance.UiPathPlatformGovernanceProvider``
  mention; replaced with neutral "concrete provider" language.
- ``submit()`` docstring no longer names ``resolve_trace_id`` — describes
  contextvars propagation generically.
- ``native/_yaml_to_index.py`` module docstring drops "platform host" →
  "host".
- ``native/models.py`` ``CheckContext`` docstring drops "platform
  boundary" → "wire-side provider at HTTP-call time".
- ``runtime.py`` module docstring drops "platform host" / "platform-side
  governance service" → "host CLI" / "injected provider".
- ``_audit/base.py`` ``AuditEvent`` docstring stops naming
  ``resolve_trace_id``; ``AuditManager`` + ``_register_traces_sink`` +
  ctor docstrings replace "platform-mandated" / "platform-owned" with
  "always-on" / "registered for every manager and cannot be disabled
  by application code".
- ``_audit/factory.py`` + ``_audit/__init__.py`` drop "platform-mandated"
  / "platform-owned".
- ``_audit/traces.py`` historical "previous version fabricated a random
  parent span_id" comment removed (PR #122 reviewer pattern); the
  "(platform default = 2, Information)" verbosityLevel comment
  renamed to "Orchestrator default" so it's not confused with the
  uipath-platform package.
- Tests: ``test_governance_runtime`` / ``test_guardrail_compensation`` /
  ``test_traces_severity`` rephrase every "platform-side" / "platform
  resolves" / "uipath-platform's own tests" mention to neutral
  provider-side wording.

Test updates from the dataclass-field removals
- ``test_evaluator.py`` ``_ctx`` helper drops ``trace_id``.
- ``test_evaluator_operators.py`` ``_ctx`` helper, the
  ``_record_context_evaluator`` ``AuditRecord`` ctor, and the six
  ``evaluate_*`` call sites drop ``trace_id``.

After this commit, ``grep -rn "platform\|UiPathPlatform\|resolve_trace_id"
src/uipath/runtime/governance tests`` returns zero matches. The runtime
layer reads as a generic governance runtime that takes an injected
``GovernanceCompensationProvider`` and doesn't name any specific
implementation or upstream package.

Depends on ``cb498cee`` in uipath-python (``EvaluatorProtocol`` +
``AuditRecord`` field drop).

Tests: ruff + mypy clean, 319 passed + 1 skipped (pre-existing
wrapper-not-present skip).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch from d505d9d to 7955499 Compare June 27, 2026 17:10
@viswa-uipath viswa-uipath force-pushed the feat/governance-foundation branch from 7c86294 to 13cd366 Compare June 27, 2026 17:31
Adds the audit pipeline that records governance evaluations: an
AuditManager that fans out per-evaluation records to registered sinks
(console + traces), with per-instance lifecycle (one ThreadPoolExecutor
+ atexit hook keyed via a WeakSet of live managers — same shape the
later GuardrailCompensator slice reuses).

Sinks
-----

- Console sink for local development and CLI runs.
- Traces sink that emits an OTel span per evaluation; severity is
  mapped from the matched rule's enforcement mode (audit / enforce /
  guardrail_fallback) so downstream traces UIs can filter by it.

Companion changes pulled in via the main-merge on this branch
-------------------------------------------------------------

This branch was kept in sync with main during review; the diff
therefore includes the following work that originated in other PRs and
will already be merged by the time this lands:

- Workspace hydration primitives (hydration, hydrator, registry_store,
  workspace; from PR #131).
- ``execution_source`` derived field on the runtime context (from
  PR #132).

Co-Authored-By: Aditi Kumari <aditi.kumari@uipath.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@viswa-uipath viswa-uipath force-pushed the feat/governance-audit branch from 7955499 to 7e4ef8d Compare June 27, 2026 17:33
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.

4 participants