diff --git a/tutorials/workflow/csharp/history-propagation/.gitignore b/tutorials/workflow/csharp/history-propagation/.gitignore new file mode 100644 index 000000000..0808c4ada --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/.gitignore @@ -0,0 +1,482 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/tutorials/workflow/csharp/history-propagation/README.md b/tutorials/workflow/csharp/history-propagation/README.md new file mode 100644 index 000000000..7f29cf6f2 --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/README.md @@ -0,0 +1,167 @@ +# Dapr Workflow History Propagation — Patient Intake (.NET SDK) + +This example demonstrates how Dapr workflows can propagate their execution +history to child workflows and activities, so downstream consumers can +inspect the full (or partial) execution context of their caller. See the +[Workflow history propagation](https://docs.dapr.io/developing-applications/building-blocks/workflow/workflow-history-propagation/) +docs for the concept overview. + +## Workflow architecture + +``` +PatientIntake (workflow) +├── VerifyInsurance (activity, no propagation) +└── PrescribeMedication (child workflow, Lineage) + ├── CheckAllergies (activity, no propagation) + ├── ScreenDrugInteractions (activity, no propagation) + ├── ComplianceAudit (child workflow, Lineage) + │ → sees PatientIntake + PrescribeMedication events + └── DispenseMedicationWorkflow (child workflow, OwnHistory) + → sees PrescribeMedication events only + → refuses to dispense if the screening lineage is missing +``` + +### Propagation scope + +| Mode | Enum value | What it sends | Use case | +|------|-----------|---------------|----------| +| **Lineage** | `HistoryPropagationScope.Lineage` | Caller's own events + any ancestor events it received | Full chain-of-custody verification (compliance audits) | +| **Own history** | `HistoryPropagationScope.OwnHistory` | Caller's own events only (no ancestor chain) | Trust boundary — downstream only sees the immediate caller (pharmacy dispense) | + +### Key demonstration + +- **ComplianceAudit** receives the full lineage via `HistoryPropagationScope.Lineage` — + it verifies that `VerifyInsurance` ran in the grandparent workflow + (PatientIntake), plus `CheckAllergies` and `ScreenDrugInteractions` ran in + PrescribeMedication. + +- **DispenseMedicationWorkflow** receives only PrescribeMedication's history via + `HistoryPropagationScope.OwnHistory`. The PatientIntake ancestral history is + excluded — the pharmacy system doesn't need (or get to see) the upstream + chain. Before dispensing, the pharmacy verifies that `CheckAllergies` and + `ScreenDrugInteractions` completed in the propagated history. + +### Scenarios + +The demo runs two scenarios back-to-back to show both the happy path and the +pharmacy's safety check: + +1. **Lineage forwarded → pharmacy dispenses.** `PrescribeMedication` calls the + dispense step with `HistoryPropagationScope.OwnHistory`. The pharmacy sees + the completed allergy and interaction screens in the propagated history and + fills the prescription. + +2. **Lineage withheld → pharmacy refuses.** `PrescribeMedication` calls the + dispense step **without** history propagation (simulating an upstream system + that fails to forward its lineage). With no propagated history to prove the + prescription was screened, the pharmacy refuses to dispense and returns a + `refused` result explaining what was missing. + +## .NET API surface + +```csharp +// Parent workflow — propagate Lineage when calling a child workflow +var result = await ctx.CallChildWorkflowAsync( + nameof(ComplianceAuditWorkflow), + input, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.Lineage)); + +// Parent workflow — propagate OwnHistory when calling a child workflow +var dispense = await ctx.CallChildWorkflowAsync( + nameof(DispenseMedicationWorkflow), + input, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.OwnHistory)); + +// Child workflow — read the propagated history +var history = ctx.GetPropagatedHistory(); // returns PropagatedHistory? + +if (history is not null) +{ + // Filter to a specific ancestor workflow by name + var prescribeEntries = history.FilterByWorkflowName(nameof(PrescribeMedicationWorkflow)); + + // Inspect events within that ancestor's segment + var completedCount = prescribeEntries.Entries[0].Events + .Count(e => e.Kind == HistoryEventKind.TaskCompleted); +} +``` + +Key types in `Dapr.Workflow`: +- `HistoryPropagationScope` — enum: `None`, `OwnHistory`, `Lineage` +- `ChildWorkflowTaskOptions` — pass `PropagationScope` here +- `PropagatedHistory` — call `.FilterByWorkflowName(name)`, `.FilterByAppId(id)`, `.FilterByInstanceId(id)` +- `PropagatedHistoryEntry` — has `WorkflowName`, `AppId`, `InstanceId`, `Events` +- `PropagatedHistoryEvent` — has `EventId`, `Kind` (`HistoryEventKind`), `Timestamp` +- `HistoryEventKind` — enum including `TaskScheduled`, `TaskCompleted`, `TaskFailed`, etc. + +> **Replay safety**: workflow code runs many times during durable execution. +> Guard side-effecting calls — including `Console.WriteLine` — with +> `if (!ctx.IsReplaying)` so they only fire on the live execution, not on each +> replay. + +## Running this example + + 1. Requires Dapr `1.18.0+` (workflow history propagation), + 2. `Dapr.Workflow 1.18.0+`, and the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) + (or newer). Redis is started automatically by `dapr init`. + 3. Build the example: + + ```bash + dotnet build ./order-processor + ``` + + 4. Run the demo: + + + +```bash +dapr run -f . +``` + + + +--- + +The app runs both scenarios once and exits on its own — no Ctrl+C needed. + +In scenario 1 (lineage forwarded) you'll see the pharmacy dispense: + +``` +[ComplianceAudit] Received propagated history with 2 segment(s): +[ComplianceAudit] APPROVED (risk=0.10, total events inspected=...) +[DispenseMedication] Dispense request: amoxicillin 500mg for P-1042 (propagated history: ... events) +[DispenseMedication] DISPENSED: rx-P-1042-... +``` + +In scenario 2 (lineage withheld) the pharmacy refuses: + +``` +[PrescribeMedication] Step 4: DispenseMedicationWorkflow child wf + -> NO history propagation (negative scenario) +[DispenseMedication] Dispense request: penicillin 500mg for P-2087 (propagated history: none) +[DispenseMedication] REFUSED — no propagated history; cannot verify screening for P-2087 +[PrescribeMedication] Step 4 BLOCKED: pharmacy refused to dispense (missing lineage: no propagated history received from prescriber) +``` + +## Standalone-mode note + +In standalone mode the sidecar will log `propagating unsigned workflow history +to ...` warnings — these are expected. Without `WorkflowHistorySigning` enabled, +propagated history chunks aren't cryptographically signed, which is fine for a +local `dapr run` demo. Signing the chunks within an mTLS trust boundary is a +production concern handled at the cluster/control-plane level and is out of +scope for this quickstart. diff --git a/tutorials/workflow/csharp/history-propagation/dapr.yaml b/tutorials/workflow/csharp/history-propagation/dapr.yaml new file mode 100644 index 000000000..f9a079c69 --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/dapr.yaml @@ -0,0 +1,7 @@ +version: 1 +common: + resourcesPath: ../../components +apps: + - appID: patient-intake + appDirPath: ./patient-intake/ + command: ["dotnet", "run"] diff --git a/tutorials/workflow/csharp/history-propagation/patient-intake/Activities.cs b/tutorials/workflow/csharp/history-propagation/patient-intake/Activities.cs new file mode 100644 index 000000000..7a3b41e28 --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/patient-intake/Activities.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +namespace PatientIntake; + +using Dapr.Workflow; + +public sealed class VerifyInsuranceActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + Console.WriteLine($" [VerifyInsurance] Checking coverage for patient {rec.PatientId}"); + return Task.FromResult(true); + } +} + +public sealed class CheckAllergiesActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + Console.WriteLine($" [CheckAllergies] Screening {rec.PatientId} for {rec.Medication}"); + return Task.FromResult(true); + } +} + +public sealed class ScreenDrugInteractionsActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + Console.WriteLine($" [ScreenDrugInteractions] Screening {rec.Medication} {rec.Dosage:F0}mg for {rec.PatientId}"); + return Task.FromResult(true); + } +} + +public sealed class DispenseMedicationActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + var dispenseId = $"rx-{rec.PatientId}-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}"; + Console.WriteLine($" [DispenseMedication] DISPENSED: {dispenseId}"); + return Task.FromResult(new DispenseResult( + DispenseId: dispenseId, + Status: "dispensed", + EventCount: 0)); // EventCount populated by DispenseMedicationWorkflow + } +} diff --git a/tutorials/workflow/csharp/history-propagation/patient-intake/Models.cs b/tutorials/workflow/csharp/history-propagation/patient-intake/Models.cs new file mode 100644 index 000000000..79f4eaa5d --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/patient-intake/Models.cs @@ -0,0 +1,36 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +namespace PatientIntake; + +public sealed record PatientRecord( + string PatientId, + string Name, + string Dob, + string Mrn, + string Condition, + string Medication, + double Dosage, + bool ForwardLineage = true); + +public sealed record ComplianceResult( + bool Compliant, + double RiskScore, + string Reason, + int EventCount); + +public sealed record DispenseResult( + string DispenseId, + string Status, + int EventCount, + string Reason = ""); diff --git a/tutorials/workflow/csharp/history-propagation/patient-intake/PatientIntake.csproj b/tutorials/workflow/csharp/history-propagation/patient-intake/PatientIntake.csproj new file mode 100644 index 000000000..322a10fc0 --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/patient-intake/PatientIntake.csproj @@ -0,0 +1,17 @@ + + + + Exe + enable + net10.0 + enable + latest + + + + + + + + + diff --git a/tutorials/workflow/csharp/history-propagation/patient-intake/Program.cs b/tutorials/workflow/csharp/history-propagation/patient-intake/Program.cs new file mode 100644 index 000000000..abb8894e3 --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/patient-intake/Program.cs @@ -0,0 +1,110 @@ +using Dapr.Workflow; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using PatientIntake; + +var builder = Host.CreateDefaultBuilder(args) + .ConfigureServices(services => + { + services.AddDaprClient(); + services.AddDaprWorkflow(options => + { + options.RegisterWorkflow(); + options.RegisterWorkflow(); + options.RegisterWorkflow(); + options.RegisterWorkflow(); + + options.RegisterActivity(); + options.RegisterActivity(); + options.RegisterActivity(); + options.RegisterActivity(); + }); + }); + +using var host = builder.Build(); + +await host.StartAsync(); + +var workflowClient = host.Services.GetRequiredService(); + +// --------------------------------------------------------------------------- +// Run two scenarios back-to-back +// --------------------------------------------------------------------------- + +Console.WriteLine(Banner("WORKFLOW HISTORY PROPAGATION DEMO — PATIENT INTAKE (.NET)")); +Console.WriteLine(); +Console.WriteLine(" Flow: PatientIntake -> VerifyInsurance"); +Console.WriteLine(" -> PrescribeMedication (child wf, Lineage)"); +Console.WriteLine(" -> CheckAllergies -> ScreenDrugInteractions"); +Console.WriteLine(" -> ComplianceAudit (child wf, Lineage) <-- sees PatientIntake + PrescribeMedication events"); +Console.WriteLine(" -> DispenseMedicationWorkflow (child wf, OwnHistory) <-- sees only PrescribeMedication events"); + +// Scenario 1 (happy path): PrescribeMedication forwards its own history to the +// pharmacy, which verifies the upstream screening and dispenses. +await RunScenario( + "SCENARIO 1: lineage forwarded — pharmacy dispenses", + "intake-ok", + new PatientRecord( + PatientId: "P-1042", + Name: "Jane Doe", + Dob: "1985-06-12", + Mrn: "MRN-77231", + Condition: "bacterial sinusitis", + Medication: "amoxicillin", + Dosage: 500, + ForwardLineage: true)); + +// Scenario 2 (negative): PrescribeMedication dispenses WITHOUT propagating its +// history, so the pharmacy receives no lineage and refuses to dispense. +await RunScenario( + "SCENARIO 2: lineage withheld — pharmacy refuses", + "intake-missing-lineage", + new PatientRecord( + PatientId: "P-2087", + Name: "John Roe", + Dob: "1979-03-04", + Mrn: "MRN-55810", + Condition: "strep throat", + Medication: "penicillin", + Dosage: 500, + ForwardLineage: false)); + +Console.WriteLine(); +Console.WriteLine(Banner("COMPLETE")); + +await host.StopAsync(); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +// Schedules one PatientIntake run, waits for it to finish, prints the final +// result, and purges its state so the demo can exit cleanly. +async Task RunScenario(string title, string instanceId, PatientRecord rec) +{ + Console.WriteLine(); + Console.WriteLine(Banner(title)); + Console.WriteLine($" [main] Scheduling workflow instance: {instanceId}"); + + await workflowClient.ScheduleNewWorkflowAsync( + name: nameof(PatientIntakeWorkflow), + instanceId: instanceId, + input: rec); + + var state = await workflowClient.WaitForWorkflowCompletionAsync(instanceId: instanceId); + + if (state is null) + Console.WriteLine(" [main] Workflow not found!"); + else if (state.RuntimeStatus == WorkflowRuntimeStatus.Completed) + Console.WriteLine($" [main] Result: {state.ReadOutputAs()}"); + else + Console.WriteLine($" [main] Workflow ended with status: {state.RuntimeStatus}"); + + await workflowClient.PurgeInstanceAsync(instanceId); +} + +static string Banner(string msg) +{ + var line = new string('=', msg.Length + 4); + return $"{line}\n= {msg} =\n{line}"; +} diff --git a/tutorials/workflow/csharp/history-propagation/patient-intake/Workflows.cs b/tutorials/workflow/csharp/history-propagation/patient-intake/Workflows.cs new file mode 100644 index 000000000..8449acc4c --- /dev/null +++ b/tutorials/workflow/csharp/history-propagation/patient-intake/Workflows.cs @@ -0,0 +1,303 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +namespace PatientIntake; + +using Dapr.Workflow; + +// --------------------------------------------------------------------------- +// PatientIntake (root workflow) +// --------------------------------------------------------------------------- + +public sealed class PatientIntakeWorkflow : Workflow +{ + public override async Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [PatientIntake] Starting intake for patient {rec.PatientId}"); + + // Step 1: Verify insurance — no propagation (plain activity). + if (!ctx.IsReplaying) + Console.WriteLine(" [PatientIntake] Step 1: VerifyInsurance (no propagation)"); + var insured = await ctx.CallActivityAsync( + nameof(VerifyInsuranceActivity), + rec); + if (!insured) + return "intake declined: insurance not on file"; + if (!ctx.IsReplaying) + Console.WriteLine(" [PatientIntake] Step 1 complete: insurance verified"); + + // Step 2: Delegate to PrescribeMedication with Lineage propagation. + // PrescribeMedication inherits this workflow's full history so its own + // grandchild ComplianceAudit can verify the complete ancestor chain. + if (!ctx.IsReplaying) + Console.WriteLine(" [PatientIntake] Step 2: PrescribeMedication child wf (HistoryPropagationScope.Lineage)"); + var result = await ctx.CallChildWorkflowAsync( + nameof(PrescribeMedicationWorkflow), + rec, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.Lineage)); + + if (!ctx.IsReplaying) + Console.WriteLine($" [PatientIntake] COMPLETE: {result}"); + return result; + } +} + +// --------------------------------------------------------------------------- +// PrescribeMedication (child workflow, level 2) +// --------------------------------------------------------------------------- + +public sealed class PrescribeMedicationWorkflow : Workflow +{ + public override async Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Starting prescription: {rec.Medication} {rec.Dosage:F0}mg for {rec.Condition}"); + + // Step 1: Allergy check (no propagation). + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 1: CheckAllergies (no propagation)"); + var allergyClear = await ctx.CallActivityAsync( + nameof(CheckAllergiesActivity), + rec); + if (!allergyClear) + return "prescription declined: known allergy"; + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 1 complete: allergy clear"); + + // Step 2: Drug interaction screen (no propagation). + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 2: ScreenDrugInteractions (no propagation)"); + var interactionsClear = await ctx.CallActivityAsync( + nameof(ScreenDrugInteractionsActivity), + rec); + if (!interactionsClear) + return "prescription declined: drug interaction risk"; + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 2 complete: no interactions"); + + // Step 3: Compliance audit grandchild workflow with Lineage propagation. + // ComplianceAudit will see both PatientIntake AND PrescribeMedication events. + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 3: ComplianceAudit child wf (HistoryPropagationScope.Lineage)"); + var audit = await ctx.CallChildWorkflowAsync( + nameof(ComplianceAuditWorkflow), + rec, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.Lineage)); + if (!audit.Compliant) + return $"prescription blocked: compliance audit failed (risk={audit.RiskScore:F2}, reason={audit.Reason})"; + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Step 3 complete: compliance audit passed (risk={audit.RiskScore:F2})"); + + // Step 4: Dispense the medication via a child workflow. + // In the happy path we attach OwnHistory propagation — the pharmacy + // receives PrescribeMedication's own events only (no ancestral chain) + // and can verify that the allergy and interaction screens ran. In the + // negative scenario (rec.ForwardLineage == false) we deliberately omit + // propagation, so the pharmacy receives no lineage and refuses. + if (!ctx.IsReplaying) + { + Console.WriteLine(" [PrescribeMedication] Step 4: DispenseMedicationWorkflow child wf"); + Console.WriteLine(rec.ForwardLineage + ? " -> HistoryPropagationScope.OwnHistory" + : " -> NO history propagation (negative scenario)"); + } + var dispense = await (rec.ForwardLineage + ? ctx.CallChildWorkflowAsync( + nameof(DispenseMedicationWorkflow), + rec, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.OwnHistory)) + : ctx.CallChildWorkflowAsync( + nameof(DispenseMedicationWorkflow), + rec)); + + if (dispense.Status != "dispensed") + { + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Step 4 BLOCKED: pharmacy refused to dispense ({dispense.Reason})"); + return $"prescription not dispensed: pharmacy refused ({dispense.Reason})"; + } + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Step 4 complete: dispensed (id={dispense.DispenseId}, {dispense.EventCount} events verified)"); + + var summary = $"dispensed: id={dispense.DispenseId}, patient={rec.PatientId}, drug={rec.Medication} {rec.Dosage:F0}mg"; + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] COMPLETE: {summary}"); + return summary; + } +} + +// --------------------------------------------------------------------------- +// ComplianceAudit (grandchild workflow, level 3) +// --------------------------------------------------------------------------- + +public sealed class ComplianceAuditWorkflow : Workflow +{ + public override Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [ComplianceAudit] Auditing prescription for patient {rec.PatientId}"); + + var history = ctx.GetPropagatedHistory(); + if (history is null) + { + if (!ctx.IsReplaying) + { + Console.WriteLine(" [ComplianceAudit] WARNING: no propagated history — sidecar may not support 1.18+"); + Console.WriteLine(" [ComplianceAudit] BLOCKED — cannot verify upstream pipeline without history"); + } + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 1.0, + Reason: "no execution history provided — cannot verify caller pipeline", + EventCount: 0)); + } + + if (!ctx.IsReplaying) + { + Console.WriteLine($" [ComplianceAudit] Received propagated history with {history.Entries.Count} segment(s):"); + foreach (var entry in history.Entries) + Console.WriteLine($" [ComplianceAudit] workflow: name={entry.WorkflowName} app={entry.AppId} events={entry.Events.Count}"); + } + + // Verify PatientIntake is present in the ancestor chain. + var intakeEntries = history.FilterByWorkflowName(nameof(PatientIntakeWorkflow)); + if (intakeEntries.Entries.Count == 0) + { + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 0.9, + Reason: $"{nameof(PatientIntakeWorkflow)} missing from propagated history", + EventCount: history.Entries.Count)); + } + + // Verify PrescribeMedication is present in the ancestor chain. + var prescribeEntries = history.FilterByWorkflowName(nameof(PrescribeMedicationWorkflow)); + if (prescribeEntries.Entries.Count == 0) + { + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 0.9, + Reason: $"{nameof(PrescribeMedicationWorkflow)} missing from propagated history", + EventCount: history.Entries.Count)); + } + + // Verify the required activity completions are recorded in history events. + var intakeEntry = intakeEntries.Entries[0]; + var prescribeEntry = prescribeEntries.Entries[0]; + + int intakeCompletedCount = intakeEntry.Events.Count(e => e.Kind == HistoryEventKind.TaskCompleted); + int prescribeCompletedCount = prescribeEntry.Events.Count(e => e.Kind == HistoryEventKind.TaskCompleted); + + if (!ctx.IsReplaying) + { + Console.WriteLine(" [ComplianceAudit] Verification:"); + Console.WriteLine($" PatientIntake TaskCompleted events: {intakeCompletedCount} (expect >= 1: VerifyInsurance)"); + Console.WriteLine($" PrescribeMedication TaskCompleted events: {prescribeCompletedCount} (expect >= 2: CheckAllergies, ScreenDrugInteractions)"); + } + + if (intakeCompletedCount == 0 || prescribeCompletedCount < 2) + { + if (!ctx.IsReplaying) + Console.WriteLine(" [ComplianceAudit] BLOCKED — required upstream checks not completed"); + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 0.9, + Reason: "required upstream checks not completed in propagated history", + EventCount: history.Entries.Count)); + } + + int totalEventCount = history.Entries.Sum(e => e.Events.Count); + double riskScore = rec.Dosage > 1000 ? 0.3 : 0.1; + if (!ctx.IsReplaying) + Console.WriteLine($" [ComplianceAudit] APPROVED (risk={riskScore:F2}, total events inspected={totalEventCount})"); + + return Task.FromResult(new ComplianceResult( + Compliant: true, + RiskScore: riskScore, + Reason: "all upstream checks verified in propagated history", + EventCount: totalEventCount)); + } +} + +// --------------------------------------------------------------------------- +// DispenseMedicationWorkflow (grandchild workflow, level 3) +// --------------------------------------------------------------------------- + +public sealed class DispenseMedicationWorkflow : Workflow +{ + public override async Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + var history = ctx.GetPropagatedHistory(); + + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] Dispense request: {rec.Medication} {rec.Dosage:F0}mg for {rec.PatientId} (propagated history: {DescribeHistory(history)})"); + + // Pharmacy policy: no lineage, no dispense. Without propagated history the + // pharmacy cannot prove the prescription was screened, so it refuses. + if (history is null) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] REFUSED — no propagated history; cannot verify screening for {rec.PatientId}"); + return new DispenseResult( + DispenseId: "", + Status: "refused", + EventCount: 0, + Reason: "missing lineage: no propagated history received from prescriber"); + } + + int eventCount = history.Entries.Sum(e => e.Events.Count); + + if (!ctx.IsReplaying) + { + // With OwnHistory only PrescribeMedication appears here — not PatientIntake. + foreach (var entry in history.Entries) + Console.WriteLine($" [DispenseMedication] workflow: name={entry.WorkflowName} app={entry.AppId} events={entry.Events.Count}"); + } + + // Verify the prescriber's own history is present and shows both screens + // completed (CheckAllergies + ScreenDrugInteractions == 2 TaskCompleted). + var prescribeEntries = history.FilterByWorkflowName(nameof(PrescribeMedicationWorkflow)); + if (prescribeEntries.Entries.Count == 0) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] REFUSED — propagated history is missing the PrescribeMedication lineage for {rec.PatientId}"); + return new DispenseResult( + DispenseId: "", + Status: "refused", + EventCount: eventCount, + Reason: "missing lineage: PrescribeMedication not present in propagated history"); + } + + int screensCompleted = prescribeEntries.Entries[0].Events.Count(e => e.Kind == HistoryEventKind.TaskCompleted); + if (screensCompleted < 2) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] REFUSED — required screening not verified in propagated history for {rec.PatientId}"); + return new DispenseResult( + DispenseId: "", + Status: "refused", + EventCount: eventCount, + Reason: "missing lineage: allergy/interaction screening not verified in propagated history"); + } + + var result = await ctx.CallActivityAsync( + nameof(DispenseMedicationActivity), + rec); + + return result with { EventCount = eventCount }; + } + + private static string DescribeHistory(PropagatedHistory? history) => + history is null ? "none" : $"{history.Entries.Sum(e => e.Events.Count)} events"; +}