Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Business policies often change faster than application releases. This architecture lets policy owners propose and review rule changes while a bounded interpreter evaluates approved versions. Copilot Studio helps with authoring, a synchronous Dataverse plug-in enforces covered writes, and an Azure function supports quality assurance (QA), app feedback, and asynchronous checks. The evaluator, rule store, test harness, and activation controls are custom components. This is a proposed architecture. Validation in the target environment remains required.
Tip
This article gives an example scenario and a generalized architecture that show how to build a domain-specific language (DSL) rule engine with Copilot Studio and Power Platform. Adapt the architecture to fit different scenarios and industries.
Architecture diagram
The architecture separates reviewed rule authoring from deterministic execution. Three runtime paths support pre-save enforcement, app feedback, and post-save and batch evaluation. Each runtime path has different authority over a write operation. The rule engine and its governance controls are custom-built.
Workflow
The workflow consists of twelve steps. Steps 1 through 7 cover the authoring phase, and steps 8 through 12 cover the runtime phase.
Business requirement and acceptance cases: The policy owner defines the requirement and approves expected outcomes before candidate generation. Version those expectations separately from the DSL. Define nulls, currencies, precision, lookup sources, and the scope of the policy. The purchase order example in the scenario details illustrates these decisions.
DSL generation: Configure the authoring agent with the grammar, field definitions, and examples. The agent drafts a candidate. A custom validation tool rejects malformed content, unsupported operators, unknown fields, and unauthorized targets. Knowledge sources and prompts do not enforce schema validity.
Independent QA: A test owner maintains the fixed acceptance and regression suites. The QA agent can propose extra cases but can't rewrite approved expectations. Keep withheld cases outside the correction prompts and use them as a final gate. Self-generated tests alone cannot establish correctness.
Test execution: An agent flow invokes an Azure Function through an authenticated custom connector. The custom harness compares actual and expected results and records the candidate hash, suite version, and evaluator build. Run parity tests against both host builds before deployment. Conversational evaluations aren't a substitute for these checks.
Bounded correction: Custom orchestration permits up to three candidate revisions and reruns required tests after each. Apply separate token, tool-call, and elapsed-time budgets. Failures, ambiguous requirements, or a failed withheld gate return to the responsible human. Passed and autofixed results describe only review outcomes, not exhaustive correctness.
Human approval: Route the requirement, candidate diff, severity, scope, and QA evidence to the policy approver. Persist a decision bound to the release content hash, suite version, and evaluator version. Changed content needs new tests and approval. Rejection or timeout can't activate a release. Power Automate handles routing. Binding and validation use custom logic.
Activation: A guarded server-side operation verifies and seals the approved release, then conditionally updates one rule-set pointer with IfRowVersionMatches. A competing update fails and goes to review. Both hosts resolve the active pointer at evaluation start. In-flight evaluations retain their selected version. Application guards protect historical content. Dataverse records are not inherently immutable.
Pre-save enforcement: Register a synchronous PreValidation plug-in for supported Create and Update messages on governed tables. Merge partial updates with selected pre-image or retrieved values, preserving explicit nulls. Resolve trusted lookup data and reject Critical or EvaluationError with a safe InvalidPluginExecutionException message. Initial PreValidation precedes platform security checks. Use a least-privilege execution identity.
App feedback: The app calls a flow and authenticated connector to the Azure Function before submission. Feedback can stop that app's submission, but other clients can bypass it, and data might change. Every supported target write must therefore pass the server-side gate again.
Post-save checking: A Dataverse-triggered flow runs after the original save. It can flag a record, queue remediation, or stop a downstream process that honors validation state. It can't cancel the original save. Apply result updates conditionally against the evaluated record version and exclude status-only changes from the trigger.
Batch evaluation: A scheduled flow submits bounded chunks. Resolve one release per request and return per-record results. Promotion from staging still passes target table enforcement. A batch pass doesn't reserve a later successful write. For a job-wide fixed release, persist its ID explicitly and authorize that mode.
Outcome handling: Pass and Warning continue through other platform checks. Warning display and acknowledgement are custom user interface and workflow features. Critical rejects only on the synchronous path. Asynchronous violations require remediation. EvaluationError never means Pass. Persist idempotency keys for retry deduplication. Rejection evidence mustn't depend on a log row in a rolled-back transaction.
Supported write paths: The following considerations apply across the runtime paths. Test each app, API, import, and bulk path before declaring coverage. Verify table and message support and merged single or bulk pipelines. Update filters must include all permitted dependencies, or evaluate all updates. A later step must not alter validated fields without another check. Use an ordered PreOperation guard after known mutators if needed. Related row changes don't trigger this row's plug-in. Cross-record reservations and concurrency invariants need separate transaction design. Restrict bypass privileges and treat administrators as trusted operators.
Components
The following components implement the workflow. Platform services provide hosting, storage, identity, and orchestration. The rule semantics and release controls remain custom-built.
| Component | Role and implementation boundary |
|---|---|
| Copilot Studio | AI agents draft expressions and propose supplementary tests through constrained tools. The agents can't approve releases or change fixed expected outcomes. |
| Power Apps canvas apps | Canvas apps and optional Teams review provide requirement entry, DSL preview, simulation, QA inbox, and approval evidence. |
| Power Automate approval workflows | Power Automate routes approvals. The review view is custom. |
| Microsoft Dataverse | Dataverse stores the rules and supports the activation operation. A guarded server operation verifies approvals and conditionally changes the active pointer. |
| Dataverse plug-ins | Use shared evaluator source and compatible dependencies in both host builds. Keep plug-ins stateless. Include assemblies, registrations, and selected images in deployment. |
| Azure Functions | Host QA and external runtime checks. Use a supported isolated .NET worker build and an explicit Microsoft Entra-authenticated connector connection. |
| Power Automate runtime flows | Handle post-save checks, bounded batches, remediation, and downstream validation state. These flows do not participate in the original save transaction. |
| Application Insights | Monitor Azure Functions execution and custom dimensions. Persist business outcomes and decisions separately. QA and flow metrics need explicit instrumentation. |
| Application lifecycle management and data policies | Promote solution components and govern connector combinations with data loss prevention policies. Managed Environments is optional and subject to licensing. It isn't API authorization. |
Minimum Dataverse data model
Table names are illustrative custom names. Use lookups for relationships and restrict deletion of referenced release evidence. Custom server guards and permissions seal approved content. Privileged admins remain a trust boundary.
| Custom table | Key fields and relationships | Authorized writer |
|---|---|---|
| RuleVersion | rule_id and version; schema; expression; dependencies; severity; content_hash | Authoring service for drafts; guarded seal operation |
| AcceptanceSuite and AcceptanceCase | suite_id and version, linked to requirement version; case input; expected outcome; approval identity | Test owner; agents can propose cases in separate drafts |
| QARun | run_id, linked to release or candidate hash, suite and evaluator versions; case results; attempts | Test harness; append completed evidence |
| RuleSetRelease | release_id, linked to exact RuleVersion set, required suites, compatible evaluator, content_hash; lifecycle_state | Release service through guarded transitions |
| ApprovalDecision | decision_id, linked to release_hash, suite and evaluator versions; approver; decision; timestamp; expiry | Approval adapter from authenticated decision |
| RuleSetPointer | rule_set_id, linked to active_release_id; row version for conditional update | Activation operation only |
| EvaluationOutcome | correlation_id, record version and release; outcome; input evidence reference; processing status | Runtime evidence writer; deduplicate retries |
Release state transitions
The pointer determines activity, not a separate Active flag on each rule. Once sealed, release content can't be edited. Operational selection and retirement metadata must not change the content hash.
| Transition | Authority and required checks | Failure behavior |
|---|---|---|
| Draft to Tested | Harness: validate grammar and dependencies. Required cases and parity requirements pass for the exact content hash. | Keep draft; return failures to author or test owner |
| Tested to Approved | Policy approver: authenticated decision binds hash, suite and evaluator versions; approval still valid | Rejected or expired: no activation |
| Approved to Sealed | Release service: revalidate evidence and install content write and delete guards | No pointer change |
| Sealed to Selected | Activation operation: compatibility and approval checks; conditionally update pointer row version | Concurrency conflict: reload and review. Don't blindly overwrite. |
| Selected to Superseded | Activation selects another sealed release. Preserve the previous release and all decisions. | Existing evaluations finish on their selected version |
| Rollback or retirement | Select a compatible approved prior release, or a new release omitting retired rules, through the same operation | Never edit historical content to simulate rollback |
Architecture alternatives
| Option | Choose when | Boundary |
|---|---|---|
| Dataverse business rules | Supported conditions and actions and server table scope meet the policy | Verify scope and actual operations. Form-scoped rules do not provide universal enforcement. |
| Custom plug-in without a DSL | Policies are stable and owned by developers | Simpler runtime, but policy changes require code deployment. |
| Power Automate or Logic Apps checks | Checks are advisory, scheduled, or post-save and action or connector costs are acceptable | Parallel processing is supported. External orchestration isn't a synchronous save hook. |
| This governed DSL design | Rules change often within a bounded grammar and need reviewed releases across apps | Adds custom parser, schema, approval, activation, and test maintenance. |
| AI in the runtime decision | The workload intentionally accepts probabilistic assistance with appropriate oversight | Different decision model. This architecture uses deterministic runtime evaluation. |
Scenario details
Use this pattern when frequently changing policies fit a small, typed grammar and need a governed release process across several applications. Changes within that grammar can ship as rule-data releases. New operators, dependencies, permissions, and plug-in registrations remain software changes. Prefer native rules when their scope and supported actions meet the need.
Purchase order example
The following purchase-order example uses synthetic values and fixed illustrative expectations. A business owner approves the policy and test suite before adoption. The example focuses on the bounded grammar used for this purchase-order policy.
| Decision | Example contract |
|---|---|
| Requirement | If the purchase total exceeds the requestor's approval limit, assign a secondary approver. |
| Scope | Create and Update on prefix_purchaseorder; presence check only. Approver eligibility and budget reservation are separate policies. |
| Input semantics | USD only; nonnegative decimal values with at most two fractional digits. Resolve the limit from trusted requestor data. Missing limit, unsupported currency or precision, or an empty approver identifier returns EvaluationError. |
| Rule | IF totalvalue > requestor.approvallimit AND secondaryapprover IS NULL THEN FAIL |
| Version bundle | A release binds the rule, schema, evaluator, and acceptance suite versions. A content hash identifies the exact manifest and rule content. |
| Gate | Critical means this rule was violated; EvaluationError means evaluation did not complete. Both reject a covered write. Pass continues to other Dataverse checks. |
Acceptance cases: The approval limit is USD 1,000.00 except where stated. Store expected outcomes before candidate evaluation.
| Case and input | Expected | Purpose |
|---|---|---|
| A1: 999.99; no approver | Pass | Below the limit |
| A2: 1,000.00; no approver | Pass | Equality boundary |
| A3: 1,000.01; no approver | Critical | Above limit without approval assignment |
| A4: 1,000.01; approver-02 | Pass | Assigned approver; eligibility is outside this rule |
| A5: limit missing | EvaluationError | Never assume a missing authoritative limit is zero |
| A6: EUR input | EvaluationError | No implicit currency conversion |
| A7: total 1,000.001 | EvaluationError | Reject unsupported precision |
| A8: empty approver ID | EvaluationError | Empty text is invalid input, not an assigned approver |
| Lifecycle point | Expected behavior and evidence |
|---|---|
| Candidate and independent test | A candidate using >= is wrong at equality. A weak suite with A1, A3, and A4 passes it, but A2 in the fixed suite rejects it. |
| Correction and review | Change >= to >, rerun the suite, and retain the diff and test report. This example requires human approval; passing tests cannot activate it. |
| Approval and activation | Bind the decision to the tested release. A successful conditional pointer update selects the approved release. Stale approval or a pointer conflict prevents activation. |
| Invalid covered save | For A3, the plug-in throws before the main operation. Check that the record wasn't created or that an existing row remained unchanged. This behavior still requires an integration test. |
| Advisory and post-save checks | App feedback reports A3 before submission. An isolated post-save-only test saves A3 first, then flags it. Check that the original row remains saved. |
| Recovery | Correct the purchase order and resubmit through enforcement. If the policy is defective, approve and select a compatible earlier release. Neither action rewrites historical evidence. |
DSL schema and evaluation contract
The schema below is a proposed custom contract, not a built-in Dataverse rule format. Store structured metadata separately from the expression. Validate an allowlisted grammar and typed inputs; never execute generated source or unrestricted eval. Bound expression length and depth, operator count, collection size, lookup count, and evaluation duration.
| Rule field | Type and owner | Constraint |
|---|---|---|
rule_id and version |
String and integer; authoring service | Stable rule identity; append a new version for any content change. |
schema_version |
Integer; engineering | Reject unsupported schema versions. |
target_table and operations |
Allowlisted names; engineering | Must match deployed enforcement registrations. |
category and severity |
Enums; policy approver | A caller can't use category to omit mandatory checks. Severity is Warning or Critical. |
expression and dependencies |
DSL string and field list; author and validator | Grammar permits only supported typed operators and known fields. Dependencies determine required images, reads, and registration review. |
message_code and public_label |
Strings; reviewer | Map to safe user text. Don't disclose protected lookup values. |
content_hash |
Digest; validation service | Hash a defined canonical serialization. Recompute the hash on the server and bind approval to it. |
Interface boundary: The Azure Function exposes a custom validation operation. The server determines the authenticated identity and allowed rule scope instead of relying on a user ID or category in the request. The plug-in calls the evaluator locally and constructs the same normalized input after resolving authoritative values.
| Message fields | Producer | Required behavior |
|---|---|---|
Request: correlation_id, mode, target_table, and operation |
Caller; server validates | Allow only QA, simulation, post-save, or batch operations granted to the authenticated connection. |
Request: records[] with record_id, record_version, values |
Caller or trusted adapter | Bound the count and request size. For saved records, get authoritative values and record version together. For simulation, identify values as proposed input. |
Request: candidate_version or release_id |
QA service or authorized batch worker | QA may select a protected candidate. Normal runtime resolves active release server-side. Don't allow arbitrary old-release bypass. |
Response: release_id, evaluator_version, and correlation_id |
Evaluator host | Identify the selected release and build for every completed evaluation. |
Response: per-record outcome, rule_id, message_code, field_refs |
Evaluator | Outcome is Pass, Warning, Critical, or EvaluationError. Apply deterministic severity aggregation; any evaluation error prevents aggregate Pass. |
Failure: authorization, transport, timeout, throttling |
API or caller | An absent or failed response isn't a business Pass. Use bounded retry for retryable failures; app feedback shows unavailable and asynchronous work remains pending or in an error state. |
Reproducibility: Record the release and evaluator version plus the normalized input or a protected reference to the input snapshot, according to the retention policy. A record ID alone cannot reproduce an evaluation after lookup data changes. Determinism applies to the complete resolved input, not merely the target row.
Considerations
These considerations implement the pillars of Power Platform Well-Architected, a set of guiding tenets that improve the quality of a workload. Learn more in Microsoft Power Platform Well-Architected.
Reliability
Fail closed and recover: If the plug-in can't resolve a required release or input, return a safe validation-unavailable error. Asynchronous work remains pending or in error with bounded retries and an operator queue. Define a separately authorized exception process. Never silently convert a failure into Pass.
Release verification: Check approval expiry, sealed content, schema/evaluator compatibility, and the exact required suite results at activation. Test stale approvals, candidate changes, competing pointer updates, failed activation, and rollback. Revalidate when the evaluator build changes.
Independent evidence: The test owner defines expected outcomes independently of the candidate generated by the authoring agent. A custom test harness compares the candidate's results against these fixed expectations. Candidates with mismatched results return for correction. Candidates that pass the required tests can proceed to human review, but passing the tests alone doesn't approve or activate a release.
| Verification | Expected evidence | Current status |
|---|---|---|
| Independent acceptance suite | Fixed acceptance cases produce the expected outcomes, and invalid rule syntax is rejected. | Example acceptance cases tested |
| Plug-in enforcement | Invalid Create absent; invalid Update unchanged; verify apps, API, imports, bulk, partial updates, and bypass controls | Target-environment test required |
| Post-save distinction | In an isolated table or path without the save gate, persist invalid input, trigger the flow, and verify remediation without rollback | Target-environment test required |
| Two-host parity and activation | Same resolved inputs/releases match in both builds; stale or changed approvals and pointer conflicts cannot activate | Target-environment test required |
| Identity and resilience | Reject wrong audience, scope, or caller; verify renewal, denied record access, timeouts, stale results, and duplicate events | Target-environment test required |
Security
Flow-to-Function identity: Configure the custom connector with Microsoft Entra delegated OAuth, the API scope, redirect URI, consent, and a governed connection referenced by solution flows. This baseline uses a service account connection. Restrict who can invoke it and which validation operations and targets it can access. Payload user IDs aren't authenticated identities.
API authorization: Require Microsoft Entra authentication for Azure App Service and validate the intended tenant, audience, scope, client, and account. Public HTTPS is the baseline; private connectivity needs a verified route. Don't expose arbitrary record queries or protected lookup values. Test unauthorized callers and connection renewal.
Service credentials: Configure managed-identity federation for custom connectors to replace the connector's client secret while retaining delegated user authentication and follow the documented single-tenant requirements. For Function-to-Dataverse access, use a separate Dataverse application user with a minimal role and governed certificate credential. The Dataverse plug-in uses the execution-context organization service. A shared connection doesn't automatically propagate end-user record permissions.
Separation of duties and audit: Separate authors, test owners, approvers, activation, runtime readers, and evidence writers. Server guards protect sealed content and pointer updates. Enable Dataverse auditing at environment, table, and relevant column levels. Set retention, restrict audit deletion, and restrict bypass of custom business logic. Administrative auditing is distinct from execution evidence and immutable archival storage.
Operational Excellence
Deployment and rollback: Co-version evaluator source, schema, host packages, registrations, and connector contract. Promote compatible components through controlled environments. Rule-data releases follow the separate lifecycle described earlier in this article. Operators need runbooks for failed evaluations, expired connections, stale jobs, and rollback; assign the policy owner responsibility for suspected business defects.
Versioned cache: Cache protected content by release and evaluator version, but resolve the active pointer at evaluation start. Cache hits don't eliminate pointer or authoritative lookup reads. Bound per-instance cache memory and lifetime. Keep historical versions and reports under a retention policy and prevent accidental cascade deletion.
Monitoring and evidence retention: Track errors and latency separately for both hosts. Add custom QA, approval, and flow metrics. Use Azure Functions monitoring to alert on failed release loads, stale pending work, and unusual escalation volume. Application Insights sampling isn't a complete business ledger. Plug-in traces can survive rollback when enabled, but are short-lived diagnostics; durable rejection evidence needs an explicitly implemented export or capture path.
Interpreting metrics: Report first-attempt passes, correction successes, escalations, and activation failures separately. A Critical outcome might show correct enforcement. Only reviewed false acceptances or rejections indicate policy defects. Investigate high correction rates before attributing them to prompt quality.
Performance Efficiency
Payload and concurrency budgets: Power Automate has a documented general message limit of 100 MB and supports Apply to each concurrency from 1 through 50, subject to connector constraints. These are limits, not recommended batch sizes. Partition below the smallest actual path limit and benchmark throttling, action consumption, and latency.
Copilot and long-running work: Copilot Studio connector payload limits are separate: 5 MB in public cloud and 450 KB in GCC. Keep immediate QA responses compact and store detailed reports. For work exceeding caller response windows, build persisted job status and bounded workers. A job ID alone doesn't run the job. Check licensing, cloud availability, connector limits, and timeouts in the target environment.
Measured targets: Runtime hosts make no model calls, but still incur compute, connector, storage, and telemetry costs. Measure end-to-end p50/p95, host startup, authoritative reads, rule or record counts, cache loads, and batch sizes. Don't assume sub-100-ms saves or savings without measurements.
Experience Optimization
Review and escalation: Show the original requirement, readable diff, required test results, and attempted corrections. Link detailed evidence while keeping withheld cases restricted to the test owner. Failed QA returns to a named owner with an actionable reason.
Runtime feedback: Apps display safe rule labels and field references. Plug-in errors explain correction or validation unavailability without revealing protected thresholds. Asynchronous checks display pending or remediation states. Test accessibility and clarity with representative users; UI feedback does not replace enforcement.
Responsible AI
Transparency: Show candidate changes and test evidence, including corrections; label examples and incomplete checks clearly.
Accountability: The policy owner stays responsible for meaning and approval. Keep authenticated decisions, versions, and test evidence under an explicit retention policy.
Fairness: Test representative affected groups and equivalent cases. Passing technical tests doesn't prove the policy is fair.
Reliability and safety: Treat generated content as untrusted until parser, type, bounded-execution, and independent tests pass. Enforce correction budgets outside the agent, and route ambiguous cases to people.
Privacy and security: Use synthetic or minimized examples, and restrict access to prompts, transcripts, tool outputs, flow history, and logs. Make sure agents can't change approved expectations or release authority.
Inclusiveness: Give people accessible authoring and review interfaces, plain-language failure messages, and a human route if they can't write or read the domain-specific language (DSL).
Next steps
Select a pilot: Choose one bounded policy and ask its owner to approve the example semantics and acceptance suite. Use the implementation contracts in this article to build and deploy the required custom components.
Review integration evidence: Complete the verification matrix in the target environment before you extend the rule catalog. Agree on measured operating targets, support ownership, and rollback readiness.
Contributors
Microsoft maintains this article. The following contributors wrote this article.
Principal authors:
- Summit Bajracharya, Microsoft MVP, Power Platform
Related resources
Copilot Studio
Power Automate, Logic Apps, and connectors
- Power Automate limits and configuration
- Power Automate approval workflows
- Dataverse trigger callback registration
- Custom connector Microsoft Entra authentication
- Logic Apps loops and parallel processing
Dataverse and plug-ins
- Write a Dataverse plug-in
- Register plug-ins and entity images
- Dataverse event framework
- Handle exceptions in a plug-in
- Dataverse optimistic concurrency
- Plug-in tracing and retention
- Dataverse OAuth and application users
- CreateMultiple and UpdateMultiple plug-ins
- Bypass custom business logic
- Dataverse business rules
- Manage Dataverse auditing
Azure Functions
- Function app Microsoft Entra authentication
- Azure Functions isolated .NET worker
- Azure Functions monitoring