diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 0000000..7362f43 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,7 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +[[profile.default.overrides]] +# File-backed end-to-end latency assertions must not compete with other tests. +filter = 'binary(=runtime_options_test) & (test(=test_fast_polling) | test(=test_default_polling_frequency))' +threads-required = "num-test-threads" diff --git a/CHANGELOG.md b/CHANGELOG.md index 8285c47..6c65478 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.2.1] - 2026-11-25 + +**Release:** + +Includes [#64](https://github.com/microsoft/duroxide/pull/64). + ### Added - **Foreign-runtime lifecycle integration** - Add fallible preparation and startup, diff --git a/Cargo.toml b/Cargo.toml index a6ed39d..ee73382 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "duroxide" -version = "0.2.0" +version = "0.2.1" edition = "2024" description = "Durable code execution framework for Rust" license = "MIT" diff --git a/README.md b/README.md index dd75a74..01b0d63 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ [![Crates.io](https://img.shields.io/crates/v/duroxide.svg)](https://crates.io/crates/duroxide) [![Documentation](https://docs.rs/duroxide/badge.svg)](https://docs.rs/duroxide) -> **[Latest Release: v0.2.0](https://crates.io/crates/duroxide/0.2.0)** — Activities can defer work until resources are available without holding a worker slot. SQLite prevents deferred work from starving ready items, and workers retry transient errors when acknowledging activity results. -> See [CHANGELOG.md](CHANGELOG.md#020---2026-11-19) for release notes and provider upgrade requirements. +> **[Latest Release: v0.2.1](https://crates.io/crates/duroxide/0.2.1)** — Fallible worker startup, passive stop/fault observation, and explicit cleanup outcomes. Runtime-owned tasks and registered foreign cleanup remain owned until they end. +> See [CHANGELOG.md](CHANGELOG.md#021---2026-11-25) for release notes. Upgrades from 0.1.x must also follow the [0.2.0 provider notes](CHANGELOG.md#provider-notes-for-020). > > **Release policy:** Official packages are published through Microsoft-managed > internal pipelines. Repository GitHub Actions are validation-only. See @@ -47,17 +47,17 @@ and [Temporal](https://temporal.io/). ```toml [dependencies] -duroxide = { version = "0.2", features = ["sqlite"] } # With the bundled SQLite provider +duroxide = { version = "0.2.1", features = ["sqlite"] } # With the bundled SQLite provider # OR -duroxide = "0.2" # Core only — bring your own Provider +duroxide = "0.2.1" # Core only — bring your own Provider ``` ## Examples ### Hello world -The fallible lifecycle calls below are **unreleased**. Use the source build -containing these changes; the published 0.1.32 crate does not have them. +The fallible lifecycle calls below require Duroxide **0.2.1 or later**. +Matching .NET, Node, and Python SDK updates remain unreleased. ```rust use std::sync::Arc; @@ -102,7 +102,9 @@ rt.shutdown_with_grace(std::time::Duration::from_secs(1)).await?; # } ``` -### Worker lifetime (unreleased) + + +### Worker lifetime Use `Runtime::prepare` followed by `Arc::clone(&runtime).start_execution().await` to handle startup errors without a panic. Preparation does not start work or @@ -140,7 +142,7 @@ before replacing a failed worker. Legacy `shutdown(None)` still uses one second of grace and returns `()` after cleanup. It has no total deadline and logs operational failures. SDK nanosecond transport limits do not restrict native grace. See the -[lifecycle guide](docs/ORCHESTRATION-GUIDE.md#worker-lifecycle-unreleased) for +[lifecycle guide](docs/ORCHESTRATION-GUIDE.md#worker-lifecycle) for validation, provider I/O, and language-adapter boundaries. ### Surviving crashes diff --git a/docs/ORCHESTRATION-GUIDE.md b/docs/ORCHESTRATION-GUIDE.md index c06496b..182aaf5 100644 --- a/docs/ORCHESTRATION-GUIDE.md +++ b/docs/ORCHESTRATION-GUIDE.md @@ -24,8 +24,7 @@ ### Minimum Viable Orchestration -The fallible lifecycle in this example is **unreleased**, requiring a matching -source build rather than published 0.1.32. +The fallible lifecycle in this example requires Duroxide **0.2.1 or later**. ```rust use duroxide::{ActivityContext, OrchestrationContext, OrchestrationRegistry, Client}; @@ -81,7 +80,9 @@ async fn main() -> Result<(), Box> { } ``` -### Worker lifecycle (unreleased) + + +### Worker lifecycle `Runtime::prepare` validates configuration and returns an `Arc` without starting work. It does not call the provider. `start_execution` requires a Tokio executor. @@ -165,7 +166,9 @@ Legacy `shutdown(None)` retains the unit return and one-second grace; `Some(0)` requests immediate force. Both wait for actual cleanup without a total limit. They log operational failures instead of raising shutdown-timeout panics. -### Native stop observation (unreleased) + + +### Native stop observation Use `Runtime::stop_status()` to read the current stop state. Use `Runtime::stop_observer()` to obtain an owned, read-only `RuntimeStopObserver`. @@ -237,7 +240,7 @@ Contained user-cleanup incidents use native tracing, not stop-state notification ### Fault shutdown and recovery -The unreleased core contains cleanup panics at named user-code boundaries: +Since 0.2.1, the core contains cleanup panics at named user-code boundaries: destruction of an activity future or application admission guard, and destruction of an orchestration driver after a valid, finalized turn decision in Runtime-owned replay. Core obligations keep their independent completion and @@ -265,7 +268,7 @@ This can interrupt unrelated work already admitted by the same worker. There is no general recovery or configurable catch-and-continue mode. Each contained incident emits a protected -[native cleanup diagnostic](observability-guide.md#contained-user-cleanup-incidents-unreleased). +[native cleanup diagnostic](observability-guide.md#contained-user-cleanup-incidents). It does not set `Faulted`. A failure in diagnostic reporting remains a Runtime fault. Passive stop observation is not an incident stream or a health check. @@ -376,7 +379,7 @@ This contract does not cover unregistered continuations. The .NET adapter registers its handler root and SDK continuations. The Node and Python adapters do not provide that additional guarantee. -Production [retirement diagnostics](observability-guide.md#pending-foreign-retirements-unreleased) +Production [retirement diagnostics](observability-guide.md#pending-foreign-retirements) report pending foreign completions separately from durable workload metrics. A zero count is never permission to release resources. diff --git a/docs/observability-guide.md b/docs/observability-guide.md index 3864e87..8f50dcf 100644 --- a/docs/observability-guide.md +++ b/docs/observability-guide.md @@ -195,7 +195,7 @@ All metrics follow Prometheus naming conventions with `_total` for counters and | `duroxide_orchestration_poison_total` | Counter | Orchestration | _(none)_ | Confirmed poison acknowledgements | | `duroxide_orchestration_poison_failed_total` | Counter | Orchestration | _(none)_ | Poison acknowledgements that returned an error after retries | | `duroxide_active_orchestrations` | Gauge | Orchestration | _(none)_ | **Current** active count | -| `duroxide_pending_foreign_retirements` | Gauge | Runtime lifecycle | _(none)_ | Aggregate independently retained foreign completions (unreleased) | +| `duroxide_pending_foreign_retirements` | Gauge | Runtime lifecycle | _(none)_ | Aggregate independently retained foreign completions (since 0.2.1) | | **Activity Execution** | | `duroxide_activity_executions_total` | Counter | Activity | activity_name, outcome, retry_attempt | Track success/failure rates | | `duroxide_activity_admission_deferrals_total` | Counter | Activity | activity_name, tag | Track admission deferrals whose abandon returned success | @@ -221,7 +221,11 @@ All metrics follow Prometheus naming conventions with `_total` for counters and **Note**: Internal dispatcher metrics use dot notation and milliseconds (not exported to Prometheus by default). -### Native stop observation (unreleased) +The native lifecycle APIs and diagnostics below require Duroxide 0.2.1 or later. + + + +### Native stop observation `Runtime::stop_status()` reports `NotRequested`, `Requested`, or `Faulted`. This is retained stop/fault state, not readiness or a health check. @@ -239,10 +243,12 @@ can be released. Matching unreleased SDKs expose passive observers; default .NET hosting monitors its actual lifecycle owner for diagnostics only. Contained user-cleanup incidents do not set `Faulted` and are not delivered by that monitor. Native tracing reports them separately. -See [native stop observation](ORCHESTRATION-GUIDE.md#native-stop-observation-unreleased) +See [native stop observation](ORCHESTRATION-GUIDE.md#native-stop-observation) for the state contract, cancellation rules, example, and ownership diagram. -### Contained user-cleanup incidents (unreleased) + + +### Contained user-cleanup incidents Enable the native `duroxide::runtime::cleanup` tracing target at `error`. Each contained incident uses `category="contained_user_cleanup"` and @@ -271,7 +277,9 @@ stops the Runtime. No new incident observer, host-stop policy or automatic resta is provided. See [fault shutdown and recovery](ORCHESTRATION-GUIDE.md#fault-shutdown-and-recovery) for eligibility, preserved outcomes and the failures that remain Runtime-fatal. -### Pending foreign retirements (unreleased) + + +### Pending foreign retirements `duroxide_pending_foreign_retirements` counts registered foreign completions that the runtime retains independently after a turn. The existing metrics facade diff --git a/tests/common/runtime_lifecycle.rs b/tests/common/runtime_lifecycle.rs index 158451c..03c6ef1 100644 --- a/tests/common/runtime_lifecycle.rs +++ b/tests/common/runtime_lifecycle.rs @@ -46,6 +46,10 @@ pub struct Fixture { impl Fixture { pub async fn new() -> Self { let inner: Arc = Arc::new(SqliteProvider::new_in_memory().await.unwrap()); + Self::with_store(inner) + } + + pub fn with_store(inner: Arc) -> Self { let hooks = LifecycleHooks::default(); let provider = Arc::new(ControlledProvider::new( Arc::clone(&inner), diff --git a/tests/worker_reliability_test.rs b/tests/worker_reliability_test.rs index 47e36eb..d0dbb03 100644 --- a/tests/worker_reliability_test.rs +++ b/tests/worker_reliability_test.rs @@ -115,15 +115,17 @@ async fn lifecycle_fetch_and_ack_faults_preserve_activity_redelivery_at_commit_b /// 5. Activity should be redelivered and executed again (at-least-once semantics) #[tokio::test] async fn activity_reliability_after_crash_before_completion_enqueue() { - // Use SQLite store for persistence across "crash" - // Shorten worker lock lease so redelivery happens quickly after restart - // Safety: setting environment variables in tests is process-wide; we set it before creating the store - // and use a deterministic value to control lease duration. We restore it at the end of the test. - let prev_lease = std::env::var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS").ok(); - unsafe { - std::env::set_var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS", "1000"); - } + use duroxide::runtime::test_hooks::{LifecyclePoint, ProviderOperation}; + use lifecycle_support::{Fixture, bounded, entered, options}; + let (store, _temp_dir) = common::create_sqlite_store_disk().await; + let f = Fixture::with_store(store.clone()); + let held = f.hold(LifecyclePoint::ProviderEnter(ProviderOperation::AcknowledgeActivity)); + let runtime_options = runtime::RuntimeOptions { + worker_lock_timeout: Duration::from_secs(1), + ..options() + }; + let activity_calls = Arc::new(AtomicU32::new(0)); // Simple orchestration that schedules an activity and waits for completion let orch = |ctx: OrchestrationContext, input: String| async move { @@ -136,11 +138,15 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { Ok(format!("Activity result: {result}")) }; + let calls = Arc::clone(&activity_calls); let activity_registry = ActivityRegistry::builder() - .register("TestActivity", |_ctx: ActivityContext, input: String| async move { - println!("Executing TestActivity with input: {input}"); - // Simulate some work - Ok(format!("Processed: {input}")) + .register("TestActivity", move |_ctx: ActivityContext, input: String| { + let calls = Arc::clone(&calls); + async move { + calls.fetch_add(1, Ordering::SeqCst); + println!("Executing TestActivity with input: {input}"); + Ok(format!("Processed: {input}")) + } }) .build(); @@ -148,14 +154,14 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { .register("ActivityReliabilityTest", orch) .build(); - // Phase 1: Start orchestration and let it schedule the activity + // Phase 1: Execute the activity, but hold its durable acknowledgement. let store1 = store.clone(); - let rt1 = runtime::Runtime::start_with_store( - store1.clone(), + let rt1 = f.prepare( activity_registry.clone(), orchestration_registry.clone(), - ) - .await; + runtime_options.clone(), + ); + Arc::clone(&rt1).start_execution().await.unwrap(); let instance = "inst-activity-reliability"; let client1 = duroxide::Client::new(store1.clone()); @@ -175,9 +181,15 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { .await, "Activity should be scheduled" ); + entered(&held).await; + assert_eq!( + activity_calls.load(Ordering::SeqCst), + 1, + "Activity must execute before its acknowledgement is interrupted" + ); // Verify activity hasn't completed yet (we'll simulate crash before completion) - let hist_before = store1.read(instance).await.unwrap_or_default(); + let hist_before = store1.read(instance).await.unwrap(); assert!( !hist_before .iter() @@ -197,17 +209,25 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { ) ); - // Simulate crash by shutting down runtime + // Force retirement while acknowledgement is held, leaving the leased item durable. println!("Simulating crash - shutting down runtime before activity completes..."); - rt1.shutdown(None).await; - - // Small delay to ensure shutdown completes - tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert_eq!( + bounded(rt1.shutdown_with_grace(Duration::ZERO)).await.unwrap(), + runtime::ShutdownOutcome::Forced + ); + f.assert_retired(); + held.release(); // Phase 2: "Restart" system with new runtime but same store println!("Restarting system..."); let store2 = store.clone(); - let rt2 = runtime::Runtime::start_with_store(store2.clone(), activity_registry, orchestration_registry).await; + let rt2 = runtime::Runtime::start_with_options( + store2.clone(), + activity_registry, + orchestration_registry, + runtime_options, + ) + .await; // The runtime should automatically resume the orchestration and reprocess pending activities @@ -231,7 +251,11 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { } // Verify the activity actually completed - let hist_after = store2.read(instance).await.unwrap_or_default(); + let hist_after = store2.read(instance).await.unwrap(); + assert!( + activity_calls.load(Ordering::SeqCst) >= 2, + "The unacknowledged activity must execute again after restart" + ); // Debug: print all events (can be removed in production) println!("History after restart:"); @@ -260,16 +284,6 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { println!("✅ Activity reliability test passed - activity completed correctly after restart"); rt2.shutdown(None).await; - - // Restore environment - match prev_lease { - Some(v) => unsafe { - std::env::set_var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS", v); - }, - None => unsafe { - std::env::remove_var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS"); - }, - } } /// Test multiple activities with crash/recovery @@ -285,14 +299,16 @@ async fn activity_reliability_after_crash_before_completion_enqueue() { /// 4. Restart runtime and verify all activities complete successfully #[tokio::test] async fn multiple_activities_reliability_after_crash() { - // Use SQLite store for persistence across "crash" - SQLite provides atomicity - // Shorten worker lock lease so redelivery happens quickly after restart - // We restore the environment variable at the end of the test - let prev_lease = std::env::var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS").ok(); - unsafe { - std::env::set_var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS", "1000"); - } + use duroxide::runtime::test_hooks::{LifecyclePoint, ProviderOperation}; + use lifecycle_support::{Fixture, bounded, entered, options}; + let (store, _temp_dir) = common::create_sqlite_store_disk().await; + let f = Fixture::with_store(store.clone()); + let held = f.hold(LifecyclePoint::ProviderEnter(ProviderOperation::AcknowledgeActivity)); + let runtime_options = runtime::RuntimeOptions { + worker_lock_timeout: Duration::from_secs(1), + ..options() + }; // Orchestration with multiple activities let orch = |ctx: OrchestrationContext, _input: String| async move { @@ -330,12 +346,12 @@ async fn multiple_activities_reliability_after_crash() { // Phase 1: Start and wait for all activities to be scheduled let store1 = store.clone(); - let rt1 = runtime::Runtime::start_with_store( - store1.clone(), + let rt1 = f.prepare( activity_registry.clone(), orchestration_registry.clone(), - ) - .await; + runtime_options.clone(), + ); + Arc::clone(&rt1).start_execution().await.unwrap(); let instance = "inst-multi-activity-reliability"; let client1 = duroxide::Client::new(store1.clone()); @@ -359,9 +375,10 @@ async fn multiple_activities_reliability_after_crash() { .await, "All 3 activities should be scheduled" ); + entered(&held).await; // Crash before any activity completes - let hist_before = store1.read(instance).await.unwrap_or_default(); + let hist_before = store1.read(instance).await.unwrap(); assert_eq!( hist_before .iter() @@ -372,13 +389,23 @@ async fn multiple_activities_reliability_after_crash() { ); println!("Crashing with 3 pending activities..."); - rt1.shutdown(None).await; - tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert_eq!( + bounded(rt1.shutdown_with_grace(Duration::ZERO)).await.unwrap(), + runtime::ShutdownOutcome::Forced + ); + f.assert_retired(); + held.release(); // Phase 2: Restart and verify all activities complete println!("Restarting..."); let store2 = store.clone(); - let rt2 = runtime::Runtime::start_with_store(store2.clone(), activity_registry, orchestration_registry).await; + let rt2 = runtime::Runtime::start_with_options( + store2.clone(), + activity_registry, + orchestration_registry, + runtime_options, + ) + .await; // Wait for completion let client2 = duroxide::Client::new(store2.clone()); @@ -400,7 +427,7 @@ async fn multiple_activities_reliability_after_crash() { } // Verify all 3 TestActivity activities completed - let hist_after = store2.read(instance).await.unwrap_or_default(); + let hist_after = store2.read(instance).await.unwrap(); let test_activity_completed_count = hist_after .iter() .filter( @@ -414,16 +441,6 @@ async fn multiple_activities_reliability_after_crash() { ); rt2.shutdown(None).await; - - // Restore environment - match prev_lease { - Some(v) => unsafe { - std::env::set_var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS", v); - }, - None => unsafe { - std::env::remove_var("DUROXIDE_SQLITE_LOCK_TIMEOUT_MS"); - }, - } } struct AckTest {