Skip to content

Track runtime shutdown and retain foreign cleanup - #64

Open
ChrisKrawczyk wants to merge 11 commits into
mainfrom
feature/rust-dotnet-lifecycle
Open

ChrisKrawczyk wants to merge 11 commits into
mainfrom
feature/rust-dotnet-lifecycle

Conversation

@ChrisKrawczyk

@ChrisKrawczyk ChrisKrawczyk commented Oct 6, 2026 •

Copy link
Copy Markdown

Summary

Make Runtime startup, stop observation and shutdown explicit, while retaining ownership until cleanup is proven.

  • Add non-executing Runtime::prepare and fallible start_execution, including owned partial-startup rollback.
  • Use upstream TaskTracker, dispatcher handles and abort-on-drop guards. Successful Drained / Forced outcomes prove tracked execution and registered cleanup ended.
  • Finalize foreign scheduling before the durable snapshot. Retain registered cleanup independently of abortable dispatchers, and report known turn faults before later provider awaits.
  • Provide Runtime::stop_status() and an owned RuntimeStopObserver. Observation retains status metadata, not Runtime/callback ownership.
  • Contain only the named user-cleanup failures described below. Preserve actual outcomes without weakening fatal-fault handling or cleanup ownership.

The latest delivery is cc06a9e.
It follows the reviewed integration of main 4f25af2 in merge
094ef9f.
Nonblocking admission retains its deferral, attempt, routing and telemetry behavior.

flowchart TD
    Stop["Accept stop: prevent new work"] --> Grace["Allow admitted work to finish during grace"]
    Grace -->|Work finishes| Cleanup["Wait for tracked native and registered foreign cleanup"]
    Grace -->|Grace expires| Force["Abort remaining async tasks"]
    Force --> Cleanup
    Cleanup --> Result["Return Drained, Forced, or a cleanup error"]
    Cleanup -.-> Pending["Blocked work can keep cleanup pending indefinitely"]
Loading

Native grace limits the wait before force, not the total cleanup wait.
SDKs retain cleanup and separately bound their callers' waits. A timeout does not permit callback release.
Independent providers, Clients and provider token-refresh tasks keep their own lifetimes.

Cleanup policy and review focus

Containment covers consumed activity-admission values, supplied activity futures, user panic payloads, and Runtime-owned orchestration-driver destruction after a valid decision and successful required finalization. These incidents do not automatically stop unrelated work. This is not a blanket exemption for user code or a tracked-task role.

Eligible late destruction preserves the actual outer success/error or valid finalized decision. Inner readiness is not an outer return and cannot turn a failed operation into success.
Both cleanup-registration forms record the supplied observer's actual return before destruction. A returned error or later destruction failure remains Runtime-fatal but does not erase that return. A polling failure before actual return remains owned, without repoll or forced drop.

Core, reporting, finalization and registered-cleanup failures still request zero-grace shutdown of the affected Runtime. Ordinary application failures remain operation-local. Standalone replay does not acquire the Runtime-owned driver-destruction guarantee.

Each contained incident uses native tracing target duroxide::runtime::cleanup, category contained_user_cleanup, with operation identity, stage and payload disposition. It is not a stop-observer notification stream. The event excludes raw panic payloads; the separate process-wide Rust panic hook can still print them.
Payload disposal makes at most two protected attempts. cleanup-skipped means the remaining allocation was left undisposed. Destructors can block, containment does not repair application state, and unwind protection cannot recover process abort or corruption. A reporting/subscriber panic remains fatal.
Diagnostics guarantee operation correlation, not a unique Runtime-lifetime key; explicit lifetime correlation remains an optional, unapplied follow-up.

Review invocation_scope.rs, task_safety.rs, dispatchers/worker.rs and replay_engine.rs together.
Finalization precedes the final durable snapshot; eligible driver destruction follows it. A valid decision is not proof of provider commit, and a cancellation acknowledgment attempt is not a committed write. Renewal, retries, uncertain ownership, no-abandon rules and Poison disposition retain their separate contracts. Shutdown adds no transaction, compensation or exactly-once guarantee.

Earlier corrections remain: known faults precede held provider reads; observers retain only metadata; and two-turn controls distinguish normal replay from unsupported finalizer-only scheduling.
The inherited SQLite contention fix also remains: BEGIN IMMEDIATE reserves writer access on five read-before-write paths, and pool return rolls back cancellation-interrupted custom-BEGIN transactions. Rollback failures retain SQLx's reporting/discard behavior. Timeouts, attempt accounting and stored formats are unchanged. Two event fixtures establish required ordering without relaxing assertions or deadlines.

The lifecycle and recovery guide
and observability guide
describe the implemented contract. Older progress records remain marked historical.

Coordinated SDK behavior

The implementations are on microsoft/duroxide-net#21, microsoft/duroxide-node#23 and microsoft/duroxide-python#25, not published packages.

  • .NET uses the real finalization-aware bridge. Completion still requires native return, retirement-notification return, zero native context leases and managed acknowledgment.
  • An SDK-invoked, awaited Node Promise can outlive native cleanup. It is not necessarily application-detached work; no .NET-style completion barrier was added.
  • A synchronous Python callback remains owned until return, including after a shutdown timeout. Separately created application threads remain separate work.

All three SDKs provide passive metadata-only stop observation. NotRequested is not readiness, and neither status nor source closure proves cleanup.
Default .NET hosting monitors the actual selected lifecycle owner's optional capability, without activating an unused default worker. Unsupported owners receive a clear warning. Monitoring is diagnostic only: no automatic host stop, process termination or restart.
No production SDK correction was required for the exercised cleanup-policy paths; the latest SDK commits update documentation only.

Current candidate evidence: November 18-20

Recorded local execution covers the native implementation now committed here. Product Markdown was then audited without changing that implementation. The scope is Windows x64, development/unwind and SQLite/in-memory, not release or platform qualification.

Selection Result
Core runtime units and selected integrations, all-feature/default CLI modes 372 distinct cases; 712 passing executions
Six fresh real SDK native builds, instrumented and production-feature configurations 109 distinct cases; 112 passing executions
Existing Rustdoc examples 46 passed; 74 unchanged ignored examples
Independent three-model review and shared challenge 0 must-fix; 0 should-fix; 1 optional diagnostics consideration

Core formatting and all-target/all-feature Clippy passed without warnings. Default Cargo test graphs still unify test hooks; separate non-test core compilation supplies the hook-free proof. Nextest was unavailable, so the recorded Cargo fallback was used. Rustdoc retains seven unchanged link warnings.

The SDK executions comprise .NET 43 native units, 30 wrapper/managed controls, two isolated no-return controls and seven production controls; Node 7 instrumented + 8 production; Python 7 instrumented + 8 production. Three .NET cases run in both modes. Actual compiled features and loaded native hashes were checked. No final selection failed, skipped, selected zero cases, aborted or hit its watchdog.
The retained no-return controls intentionally preserve ownership at test-host exit; exit is not quiescence. Node's roughly ten-second cancellation grace and Python's unchanged five-to-six-second timeout assertion remain intact. Continued progress is not proof of a prior committed acknowledgment.

Qualified source-built SDK graph Tokio futures-util duroxide-pg
.NET 1.49.0 0.3.32 0.1.36
Node 1.54.1 0.3.34 0.1.38
Python 1.54.1 0.3.34 0.1.38

These graphs use the modified core source declaring 0.1.32, not equivalent published core 0.1.32. Python declares PG 0.1.37 but resolves 0.1.38 in its qualified graph. Original SDK pins, locks and native assets were not rewritten.
The documentation audit covered 13 product Markdown files, preserved all 320 existing code/diagram fences and checked 50 changed local links/anchors.

Earlier lifecycle and reconciliation evidence - not reruns of this cleanup-policy candidate

The earlier reconciled core passed 1,350 all-feature and 1,347 default-mode cases across 61 suites per mode, retaining one historical fixture recorder. Its unchanged exhaustive cancellation harness enumerated 587,844 cases and individually asserted 293,922; only that harness used test opt-level 2, with its original debug assertions and 180-second guard. The earlier unoptimized timeout was not counted as a pass. Separate hook-free compilation exercised seven lifecycle and three retirement-metrics controls.

Earlier SDK lifecycle/observation selections passed .NET 272 instrumented / 89 production, Node 54 / 36 with 18 hook-only skips, and Python 72 / 58 with 14 hook-only skips on each of Python 3.12 and 3.13: 711 passes and 46 explicit skips. Those builds used .NET release DLLs, Node dev addons and Python dev ABI3 wheels. They are historical source/configuration evidence, not optimized or PostgreSQL qualification of the new policy.

The October 28 record retains earlier bounded performance measurements. They are not measurements of this candidate and do not establish end-to-end performance or zero overhead.

Remaining gates

Maintainer approval, merge and compatible core publication precede final SDK registry pins, locks and native assets. Final registry-only, hosted, optimized/release-profile, supported-platform, PostgreSQL and installed-package qualification remain open.
As of this delivery, live main 14ee3a9 is one commit beyond the reviewed 4f25af2 integration. That additional commit was not merged or qualified here; reconcile later main as required before merge.

Current-head hosted CI is a separate check, not implied by local results. The earlier Node run demonstrates the registry dependency gate: published core 0.1.32 lacked the required lifecycle/observer APIs. An imported provider update does not qualify a shared production PostgreSQL migration.

No tag, release, package publication, publishing dispatch or merge into main was performed or requested. Local workflow artifacts, native binaries and unrelated work are excluded.

Generated with PAW.

Add fallible preparation and startup, immutable shutdown deadlines, and
parent-owned execution cleanup with truthful quiescence outcomes.
Retain foreign invocation cleanup, preserve durable replay decisions,
and add lifecycle diagnostics, controlled regression coverage, and docs.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
Merge main's shutdown and replay improvements. Replace the custom task tree
and total-deadline machinery with upstream tracking plus narrow activation,
fault-reporting and foreign-retirement capabilities. Preserve native grace
semantics, diagnostics, recovery coverage and checksum-verified replay fixtures.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
@ChrisKrawczyk

Copy link
Copy Markdown
Author

Upstream-first reconciliation is pushed in 82b2572 (normal merge of main, no history rewrite). GitHub reports this draft conflict-free. Native ownership now uses upstream TaskTracker, direct dispatcher handles and child abort guards; the custom task-group and core total-deadline modules are removed. Narrow fallible activation, typed actual-cleanup results and foreign finalization/retirement remain. Legacy native grace-then-cleanup and provider-cancellation semantics are preserved; SDKs own their bounded observations.

The feature-only diff falls from 6,976 to 4,774 changed lines, about 32%, excluding imported upstream fixes. The independent scoped integration review is PASS after correcting an inherited .NET concurrent-test assertion. Current core verification passed 156 focused cases (one recorder ignored); doctests passed 46 with 74 ignored. The reviewed tree exactly matches this commit.

Coordinated adapters: microsoft/duroxide-net#21, microsoft/duroxide-node#23, microsoft/duroxide-python#25. These remain draft/development integrations: published core 0.1.32 lacks the additive APIs, so approved registry dependency delivery, PostgreSQL, non-Windows/five-RID, broader regression and hosted CI gates remain OPEN. Nothing was merged, released or published.

chkraw and others added 2 commits October 21, 2026 13:57
Address the ten accepted core review findings, preserving panic compatibility and upstream lifecycle ownership. Add bounded-cardinality metrics and focused production/instrumented regressions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
@ChrisKrawczyk ChrisKrawczyk changed the title [Rust/.NET Runtime Lifecycle] Retain execution through bounded shutdown Track runtime shutdown and retain foreign cleanup Oct 21, 2026
@ChrisKrawczyk
ChrisKrawczyk marked this pull request as ready for review October 22, 2026 04:55

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Mostly good. A few issues found with the help of AI.

Also, this changes the cancellation behavior for native (Rust) a good amount, since now a panic dtor stops the whole runtime. (Admittedly, panicking in a dtor isn't great, but we do it some). Also, it adds a good amount of overhead to native use (much more locking and such). Maybe that's fine? Anyway, I'd like to take another look at it after the changes.

Comment thread src/runtime/invocation_scope.rs Resolved
Comment thread src/runtime/mod.rs Resolved
Comment thread src/runtime/replay_engine.rs Resolved
Report protected turn faults before provider awaits while retaining finalization,
valid decisions and foreign cleanup ownership. Add owned stop/fault observers,
monotonic publication and lifecycle regressions. Document normal replay and add
two-turn finalization controls without extending replay semantics.

Ref: #64 (comment)
Ref: #64 (comment)
Ref: #64 (comment)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
@ChrisKrawczyk

Copy link
Copy Markdown
Author

🐾 Implementation Reviewer 🤖:

Core review corrections are pushed in b3d6aa9. Replies on all three inline threads explain early protected fault reporting, owned native stop observation, and two-turn replay controls. The following is the updated qualification record; the PR description still contains the earlier documentation-pass snapshot.

Containment trade-off: this revision retains Runtime-wide stop for faults caught at protected internal/destruction/finalization/registered-cleanup boundaries. Ordinary application errors and handler-poll panics remain operation-local; a destructor within that catch can also fail locally. The catch boundary matters, not merely whether a Drop implementation panicked. No cleanup registration does not establish native-only isolation, because Node and Python also execute foreign callbacks without .NET's registration protocol. The guide now explicitly documents interrupted unrelated work, retries/repeated effects and the absence of automatic restart or compensation. This remains an availability trade-off for maintainer review, not a claim that every native panic requires the same policy.

Bookkeeping cost: the earlier bounded base-to-reviewed-head replay-only comparison measured +0.216 microseconds (+12.8%) for an immediate turn and +0.290 microseconds (+3.13%) for five-activity scheduling, with one additional allocation. That harness bypassed the newly changed execution handoff, so those numbers do not qualify this correction. A new matched comparison from 5109e5de to this commit exercises the actual scoped execution handoff, including the invocation guard and attachment:

Workload Previous head median Corrected median Allocation calls / cumulative requested bytes
Immediate turn 4.383 us 4.179 us 47 / 3,685, unchanged
Five-activity scheduling turn 14.645 us 14.574 us 191 / 21,203, unchanged

Five alternating timing pairs used hook-free Windows release builds, 10,000 warmups and 200,000 measured iterations per process. Allocation diagnostics ran separately. Immediate ranges were 4.369-4.398 / 4.153-4.224 us; five-activity ranges were 14.596-14.931 / 14.354-14.734 us and overlap. This finds no additional per-turn allocation or measured regression in these workloads, not a general speedup or zero-overhead claim. It excludes provider I/O, dispatcher contention, actual activity execution, foreign completion and cold Runtime/observer construction. The two harnesses are not interchangeable end-to-end measurements.

Final-core qualification: formatting and all-target/all-feature Clippy passed. The focused default-feature and all-feature runs each passed 157 cases; each Rustdoc run passed 46 with 74 existing ignored examples. Fresh .NET, Node and Python native assets were rebuilt against the same sealed core. .NET passed 37 native, 176 instrumented managed and 96 hook-free managed cases. Node passed all 37 instrumented cases and 26 hook-free cases with 11 expected hook-only skips. Python 3.12 and 3.13 each passed 52 instrumented cases and 43 hook-free cases with nine expected hook-only skips; each run includes 13 native-independent probe-support cases. The new guide example compiled and its Mermaid diagram rendered locally.

These are Windows x64 local results. SDK native assets used dev profiles; performance used hook-free release. This is compositional core/SDK ownership evidence, not proof that every SDK directly injects the same turn-destructor fault. Compatible registry pins, hosted/platform/release-package qualification, and passive SDK/default-host fault visibility remain separate gates. No merge, release or publication is requested. Review threads remain open for your assessment.

chkraw and others added 2 commits October 28, 2026 13:40
Label the replay and capability-filtering progress records as dated snapshots
and link to current guides. Remove misleading current-status wording while
preserving design rationale, recorded decisions and release history.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
Preserve actual Tokio panic identity and protected admission/handler destruction. Reserve SQLite writers before read-modify-write transactions and roll back cancelled acquisitions before pool reuse. Order duplicate-event and early-event fixtures explicitly without extending deadlines.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
@ChrisKrawczyk

Copy link
Copy Markdown
Author

Thom, we revisited the destructor-panic concern. Stopping the whole runtime isn’t a Rust requirement, and it can interrupt unrelated work or cause completed activities to run again if their results weren’t saved.

Our recommendation is to keep shutdown as the fallback where cleanup may affect shared resources, while testing narrower cases where other work can safely continue. First, we’d test giving an affected, already-completed activity a strictly bounded chance to save its result before forced shutdown.

This would still leave some destructor panics stopping the runtime. Does that seem like the right boundary, or should native cleanup panics stay local by default? A concrete example you expect the runtime to survive would help.

@thomcc-work

Copy link
Copy Markdown
Contributor

I'd draw the line on provable quiescence rather than on "may touch shared resources". A native destructor panic has already finished destruction, so nothing is left to retain. That's different from foreign cleanup, where you can't prove the work ended. I'd keep panics in user-owned activity futures, admission guards and orchestration drivers operation-local, the same as poll panics. I'd keep the Runtime stop for runtime internals and registered foreign cleanup. Users who want fail-fast already have panic = "abort". Two examples I'd expect the Runtime to survive: a cancelled activity that drops an owned Tokio runtime ("Cannot drop a runtime…"), and a guard whose Drop unwraps a mutex poisoned by an earlier local panic. Separately, one orchestration whose driver panics on drop stopped max_attempts Runtimes in a row before it was poisoned. The bounded-save change doesn't address that.

chkraw and others added 2 commits November 20, 2026 15:51
Complete the reviewed integration of main at
4f25af2 using the existing resolved
24-file index. Keep the separately reviewed cleanup-policy changes in
the working tree for their own commit.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
Contain the named activity/admission and finalized driver cleanup
boundaries, bound panic-payload disposal and report each incident.
Preserve actual outer outcomes and registered-observer return proof.
Keep core, reporting, finalization and registered-cleanup failures fatal,
and retain ownership when registered completion never returns.

Add focused regressions and document the policy and retained limits.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
@ChrisKrawczyk

Copy link
Copy Markdown
Author

🐾 Implementation Reviewer 🤖:

Thom Chiovoloni (@thomcc-work), following your feedback, the changes are pushed in cc06a9e. We adopted narrower containment, not the bounded-save proposal:

  • User-owned activity-future and admission-guard cleanup failures stay operation-local, including cancellation. Repeated contained incidents leave the original workers running.
  • Orchestration-driver cleanup is contained only after a valid turn decision and successful required finalization. Later eligible cleanup does not rewrite an actual outer result or valid decision; inner readiness does not count as a return.
  • Failures in runtime internals, reporting, finalization and registered foreign cleanup still stop the Runtime. Actual cleanup-observer return is now recorded before destruction; later destruction failure remains fatal but does not erase that return. Never-returned cleanup remains owned.

This is not blanket panic recovery: disposal can be skipped and leak, destructors can block, and preserving a result does not prove it was committed.

Core CI passed. Focused Windows/SQLite development-build qualification also passed through the real .NET, Node and Python wrappers without production SDK corrections. Final registry, platform and release qualification remain open.

Could you re-review, particularly the conditional driver boundary and the cases that remain Runtime-fatal?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A few nits, but otherwise it's good. Thanks, sorry for all the trouble.

Comment thread CHANGELOG.md Resolved
Comment thread src/runtime/task_safety.rs Resolved
chkraw and others added 2 commits November 24, 2026 16:58
Merge main's 0.2.0 release commit into the lifecycle feature branch.
Keep this PR's additions under Unreleased and preserve the published
0.2.0 release history.

Ref: #64 (comment)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
Annotate the new lifecycle, cleanup-attachment and test-hook enums
without changing their variants, derives or discriminants.

Ref: #64 (comment)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
ChrisKrawczyk pushed a commit to microsoft/duroxide-python that referenced this pull request Nov 25, 2026
Align native dependency declarations with the core/provider 0.2.0
release line. Preserve observation errors without constructing Python
exceptions off-GIL, and retain ownership when a shutdown outcome cannot
prove quiescence.

Add a focused instrumented observation regression and document the fully
drained PostgreSQL upgrade. The lifecycle APIs still require the matching
unreleased core; registry-only release qualification remains pending.

Ref: microsoft/duroxide#64 (comment)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
ChrisKrawczyk pushed a commit to microsoft/duroxide-node that referenced this pull request Nov 25, 2026
Align native dependency declarations with the core/provider 0.2.0
release line. Report unsupported stop states through observation errors
and retain callback resources when a shutdown outcome cannot prove
quiescence.

Add a focused instrumented observation regression and document the fully
drained PostgreSQL upgrade. The lifecycle APIs still require the matching
unreleased core; registry-only release qualification remains pending.

Ref: microsoft/duroxide#64 (comment)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 73748d4f-2eb6-47d2-9dbc-af8681e80e83
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants