6.8. Disposal Contract¶
VMx disposal is safe to call from independent teardown paths. If a public
VMx-owned type exposes Dispose() / dispose(), the first call claims its
terminal work and every later or re-entrant call is a no-op. Completion,
terminal notifications, cancellation, and owned-resource cleanup happen at
most once.
This rule removes the need for host-side “already disposed” flags. It does not make all later API calls behave alike: each type keeps its documented post-dispose behavior.
6.8.1. Modeled Assignment After Disposal¶
Modeled assignment has one portable terminal rule in all five flavors. An assignment that starts after disposal returns immediately. It does not compare the candidate for equality. It does not change the retained model or the snapshot. It does no modeled-hint work, validation, or command-state recomputation. It calls no consumer callbacks. It sends no local notifications and no hub messages. The last accepted model and all derived state values stay readable and unchanged.
This admission guard covers modeled components and FormVM. Modeled
composites do not expose a settable retained model—their model input
configures a child factory—so they need no separate guard.
An assignment admitted before disposal keeps its ordinary completion and notification contract. Continue cancelling network requests, renderer work, tasks, and other application operations when their resources are no longer needed; the VM guard prevents late state admission but does not replace resource cancellation.
6.8.2. The Seven Disposal Families¶
| Family | Representative surfaces | Cross-cutting ID | Detailed coverage |
|---|---|---|---|
| VM and owner cascades | Component, composite, group, aggregate, hierarchy, forwarding | DISP-001 |
AGG-007, AGG-008, COMP-045, COMP-049, COMP-050, CVM-009, HIER-030, HIER-038, HIER-041, HIER-045, LIFE-004, LIFE-005, LIFE-006, LIFE-012, LIFE-013, LIFE-018, LIFE-021, LIFE-022 |
| Commands | Relay, async relay, composite/decorator, modeled CRUD | DISP-002 |
CMD-013, CMD-016, CMDD-011..CMDD-013, CMDD-017, CMDD-019 |
| Hubs and services | Message hub, notification hub | DISP-003 |
HUB-004, HUB-012, NOTIF-017, NOTIF-020, SUBV-003 |
| Interaction owners | Form, modal, notification rendering VMs | DISP-004 |
DIA-011, FORM-014, FORM-028, FORM-034, FORM-038, FORM-042, NOTIF-017, NOTIF-018, NOTIF-019 |
| Reactive helpers | Derived property, expansion/search state, discriminator, delayed task, TreeSelection |
DISP-005 |
DLY-004, DPROP-011, EXP-008, HIER-040, SRCH-006 |
| Collection/projection helpers | Batch handles, paging, filtered projections, disposable collections | DISP-006 |
COMP-013, COMP-035, GRP-006 |
| Async resource owners | AsyncResourceVM loader, commands, and accepted value | ARES-010..011 |
— |
AggregateChangeStream disposal is covered by AGCH-010.
Only types that are documented as thread-safe support disposal that races other calls. These types claim terminal work atomically. Single-threaded flavors and helpers still support repeated and re-entrant disposal on their execution model.
6.8.3. Ownership Rules¶
- Every VM exposes its injected message hub as a read-only baseline member. The hub is shared infrastructure: VM disposal never disposes it.
- Subclass-owned, disposal-lifetime resources can be registered through
Own(C#),_own(Python), orown(TypeScript, Swift, Rust). Cleanup runs exactly once in LIFO order after the subclass disposal hook. One failing cleanup is swallowed without blocking the rest. - Registration after disposal cleans the resource immediately once.
- Reconstruct and destruct do not release disposal-lifetime registrations.
Per-construct resources remain explicit in
OnConstruct/OnDestruct. - Container VMs (composites, groups, aggregates) dispose their children
depth-first before their own teardown (
LIFE-013). With no hook running on another thread, the order is children, the container'sDisposedpublication, subclass hook, LIFO owned registrations, stream completion, then commands. A child reached through several teardown paths has one observable terminal transition. - A foreign dispose is a
dispose()call while a construct or destruct hook of the VM runs on another thread. The VM then publishesDisposedfirst and waits for that hook. After the hook returns, the VM disposes its children and members, before its subclass hook (LIFE-015, spec 02 §7, §7.1, ADR-0179). - With no hook running on another thread, the VM disposes its children and
members inline, before it publishes
Disposed. Aconstruct(),destruct(), orreconstruct()call that starts during that cascade fails with the error that the call raises on aDisposedVM. It publishes nothing and runs no hook, even when a child's or member's dispose hook makes the call. A transition that started before the cascade commits no status other thanDisposed, and its call returns as a call that disposal superseded (LIFE-021, spec 02 §7.2, ADR-0175). - A child view-model registered with the owned-resource helper is not a
container child. It is disposed parent-first: the parent publishes
Disposed, runs its subclass hook, and then disposes owned registrations, including that child, in LIFO order. - A member view-model registered with the member-disposal helper (
OwnMemberin C#,_own_memberin Python,ownMemberin TypeScript and Swift,own_memberin Rust) is disposed depth-first instead: members are disposed in registration order, after a container's own children. For a dispose that is not foreign, this happens before the parent publishesDisposed(LIFE-018, spec 02 §7.1). - A terminal cascade does not stop at a failing child or subclass hook. The teardown of every sibling still runs. The base teardown of the parent also runs. Flavors that throw or return results report the first failure only after all mandatory cleanup completes.
- Disposal deferred by an ownership transfer runs after commit or rollback.
- A committed transfer delivers both local membership events before it propagates a disposal failure. The old container sends no hub message, because its disposal is requested.
- A composite or group sends no
CollectionChangedMessageonce its disposal is requested, also when the disposal is deferred. A local subscriber or current-changed callback that disposes the container therefore suppresses the hub message of the change it observes. The local event is still delivered (spec 01 §1.4, ADR-0190). - A disposed
HierarchicalVMrefusesAddChild,RemoveChild,ReparentChild,InvalidateChildren,InvalidateSubtree, andAttachMany, also where the call would do nothing. A transfer out of a disposed parent refuses too. A refused call changes nothing and publishes nothing. Spec 18 §7.1 lists the refusal channel of each flavor (ADR-0190). - If rollback also triggers failing disposal, an earlier attachment failure stays first.
- Disposal requested from a current-changed callback is likewise deferred until selection publication finishes. Selection holds no membership transaction, so the callback never blocks on one (ADR-0173).
- Disposal that races an admitted construct or destruct hook waits until the hook settles. Terminal resource and stream teardown follow.
- Opposing hooks that cross-dispose use cycle-aware deferral. Neither thread
deadlocks, and no post-hook child work begins after the parent becomes
terminal. The admitted hook's lifecycle call runs the deferred cleanup. When
the hook succeeds, that call reports the cleanup's first failure (ADR-0200).
A hook failure stays first. The cycle-broken
dispose()returns normally. Swift disposal does not throw, so Swift reports nothing. TypeScript runs on one thread and cannot form the cycle. - A forwarding VM delegates disposal to the wrapped VM; it does not introduce
reference counting. Resources registered through a forwarding VM belong to
the wrapped VM and are released with its other registrations (
FWD-005). - Command decorators and composites do not dispose caller-owned inner commands unless their type-specific contract explicitly says they own them.
ServicedObservableCollectionandKeyedServicedObservableCollectionnever own or dispose their items and do not implement VM child-collection lifecycle interfaces.- Subscription and batch handles release only the registration or batch scope they represent.
AsyncResourceVMcancels active acquisition and releases its last accepted value on disposal. A loader that completes late cannot publish or become current; its acquired value is cleaned exactly once. Python invalidates the resource synchronously and schedules native cancellation and late-result registration on the operation loop. A caller-owned loop must stay runnable until admitted work is cancelled and drained; see Python asyncio dispatcher ownership.
6.8.4. Portable Inventory¶
This table lists the public disposal surfaces of VMx view models, commands, collections, services, and Rust subscription handles. Test-support recorders are not listed. In every row, a second or re-entrant dispose is a no-op. The table uses concept names; Flavor Exceptions lists spellings and every flavor-specific difference.
| Type | Dispose behavior | Later calls | Released | Readable state |
|---|---|---|---|---|
| VM families: component, read-only, composite, group, aggregate 1–6 | One Disposed transition; VM-local streams complete |
Lifecycle calls other than dispose fail; container changes can refuse | Children depth-first, then subclass hook, LIFO owned registrations, stream completion, commands | Status |
HierarchicalVM |
One Disposed transition; VM-local streams complete |
Lifecycle calls other than dispose fail; structural calls refuse; other changes are inert | No children, which stay live (see Disposing A Subtree); subclass hook, LIFO owned registrations, stream completion, commands | Status |
| Forwarding component and composite VMs | Delegates to the wrapped VM, which completes once | Wrapped VM contract | Delegates to the wrapped VM | Wrapped VM contract |
| Message hub | Message stream completes once | Sends are ignored | Pending transaction queue and subject | — |
| Relay command, with and without parameter | Terminal disabled state | CanExecute is false; execute is inert |
Trigger subscriptions | — |
| Async relay command | Owned error channel completes once; the active operation is cancelled | Disabled; execute is inert | One active cancellation handle and trigger subscriptions | — |
| Composite, decorator, confirmation-decorator, and modeled-CRUD commands | Owned error channel completes where present | CanExecute is false; no inner work starts |
Event subscriptions and owned relay commands only; caller-owned inner commands stay caller-owned | — |
FormVM |
Approval, error, and validation streams complete once | Approve and deny are inert | Approve and deny commands | Model and snapshot |
| Notification hub | Pending stream completes once with no final snapshot; waiters resolve Pending |
Post resolves Pending; resolve is inert; a new Pending subscription only completes |
Pending queue and waiters | — |
NotificationVM, ConfirmationVM |
Property-change stream completes once | — | Timers, pending subscription, commands | Last render state |
ModalVM |
Idempotent dismiss; completion resolves once | — | Waiters | First result |
DerivedProperty |
Value-change stream completes once | No recompute emission | Source subscriptions | Last value |
ExpandableState |
Expansion stream completes once | Mutations and commands are inert | Expansion subscribers; expand, collapse, and toggle commands that were read | Last expansion value |
TreeSelection |
Change stream completes once, without a value | Current is null; select and clear are inert |
Hub subscriptions on the watched path; never a node | — |
SearchableState |
Search streams complete once | Setters and search are inert | Search and source subscriptions | Search term reads empty |
DelayedTask |
Cancels the pending action once | Schedule and cancel are inert | The pending scheduler handle | IsPending is false |
FilteredCompositeVM, ScoredFilteredCompositeVM |
Projection stream completes once | The projection stops changing | Source subscription | Frozen visible projection |
PagedComposition |
Paging streams complete where exposed | Paging calls are inert; page reads remain | Source subscription | Page reads |
TokenPagedComposition |
Command stream completes once | Late fetch results cannot mutate or publish | Load-more and refresh commands | Accumulated state |
| Batch handles from list, composite, and group operations | At most one Reset at outer batch exit | The handle has no other behavior | One batch depth claim | — |
AggregateChangeStream |
Output subscriptions complete once | New subscriptions complete at once; membership and item changes are ignored | Structural subscription and selected item subscriptions; never source items | — |
DiscriminatorVM |
Active-change stream completes once | Mutations are inert | Stream subject | Reads |
AsyncResourceVM |
Active operation is invalidated; commands and state stream complete | Late work cannot publish | Cancellation handle; accepted or late value is cleaned once | Terminal state |
ObservableList, ObservableDictionary (Python only) |
Every VMx-owned collection subject completes once | Mutations emit nothing | Collection subjects | Stored contents |
| Hub, property-change, approval, and aggregate-change subscriptions (Rust only) | Detaches; no completion callback runs | The handle has no other behavior | One subscriber registration | — |
MessageRecorder (Rust only) |
Recording stops; the hub detaches the recorder | No later message is recorded | Hub registration | Recorded messages |
| Value streams and their subscriptions (Rust only) | Subscribers complete once; subscriptions detach | Later sends are inert | Subscribers | Last value |
In the VM families row, a container change is a composite or group membership or selection change: add, insert, remove, remove by index, replace, clear, move, or a selection. These changes can refuse after disposal; the flavor exceptions below state the result in each flavor. Every other change is inert.
In the AggregateChangeStream row, a reconciliation that runs at the same
time as disposal can hold a selected-item subscription that it staged but did
not commit. That reconciliation releases the subscription when it sees the
disposal, and the aggregate ignores its values (ADR-0214).
Rows marked "only" exist in the named flavor. Every other row applies to every flavor unless the exceptions below say otherwise.
6.8.5. Flavor Exceptions¶
6.8.5.1. C#¶
MessageHub,AsyncRelayCommand, andTokenPagedCompositionclaim disposal under a gate.NotificationHubclaims it under a lock.- VM lifecycle calls other than dispose raise. Property changes are inert.
- Composite and group
Add,Insert,Remove,RemoveAt,Clear,Move, and the indexer setter raiseObjectDisposedException. A composite selection raisesObjectDisposedException, a null clear included, unless it assigns the child that is already current, which changes nothing. RelayCommandandRelayCommand<T>can raise one finalCanExecuteChangedbefore the terminal disabled state.- The message stream is
Messages; the derived-property stream isValueChanged. Post-disposeDerivedProperty<T>writes follow the type-specific validator contract. NotificationVMandConfirmationVMstop their property-change surface. Later resolution paths are inert.- Filtered projections expose no projection stream; the projection stops
changing.
PagedComposition<T>has no completion surface. After disposal,PageSizeandCurrentPageIndexwrites and the four move calls change no state and raise noPropertyChangedevent (ADR-0214). AsyncResourceVM<T>releases its cancellation token source and loader registration.AggregateChangeStream<T>.BatchthrowsObjectDisposedExceptionafter disposal.
6.8.5.2. Python¶
- VM families claim disposal under the lifecycle lock.
MessageHubandNotificationHubuse their own locks.AsyncResourceVMuses its resource gate. - The terminal status is
DISPOSED; illegal lifecycle calls raise. - Composite and group
add,insert,remove,remove_at,clear,move, item assignment, and item deletion raiseRuntimeError. A composite selection raisesRuntimeError, a null clear included, unless it assigns the child that is already current, which changes nothing. - Commands complete their owned subjects once. The async relay command cancels one in-flight task.
NotificationHubfutures resolvePENDING, and post resolvesPENDING.ModalVMresolves its awaiting futures once.PagedCompositionandTokenPagedCompositioncomplete paging streams where exposed and release source subscriptions and paging commands. Reads remain; late token fetches cannot mutate. After disposal,PagedCompositionpage_sizeandcurrent_page_indexwrites and the four move calls change no state and emit nothing (ADR-0214).ObservableListandObservableDictionaryare disposable only in Python.AsyncResourceVMinvalidates the active operation synchronously. Native cancellation and late-value cleanup run on the operation loop; see Ownership Rules.AggregateChangeStream.batch()raisesRuntimeErrorafter disposal.
6.8.5.3. TypeScript¶
- The terminal status is
Disposed; illegal lifecycle calls throw. - Composite and group
add,insert,remove,removeAt,setAt,clear, andmovethrowError. Every composite selection afterDisposedthrowsError, a null clear and the child that is already current included. - Commands complete their owned subjects once. The async relay command aborts
one
AbortController. NotificationHubpromises resolvePending.NotificationVMandConfirmationVMrelease scheduler handles.ModalVMresolves its promise once.PagedCompositionandTokenPagedCompositionfollow the Python paging behavior above.BatchUpdateHandlealso implements[Symbol.dispose].AsyncResourceVM<T>releases an abort controller.AggregateChangeStream.withBatchthrowsErrorafter disposal.- Lifecycle hooks run on one thread, so no hook runs on another thread during
disposal. A
construct(),destruct(), orreconstruct()of a container from a child's dispose hook, or of a leaf from a member's dispose hook, throwsStatusTransitionErrorforDisposedand runs no hook, as in the other flavors (Ownership Rules).
6.8.5.4. Swift¶
ObservableListandObservableDictionaryexpose no VMx disposal member and are outside this inventory.- Publishers finish rather than complete. The terminal status is
.disposed; illegal lifecycle calls throw. - After
Disposed, a compositecurrentassignment orsetCurrent(_:)of a member ornilchanges nothing and does not throw. A non-member is still refused:setCurrent(_:)throwsCompositeMembershipError, and thecurrentsetter traps. Composite and groupaddResult(_:),insertResult(_:at:), andreplaceResult(at:with:)return.failure(.attachmentFailed). Soadd(_:)stops a debug build withassertionFailureand changes nothing in a release build, andinsert(_:at:)andreplace(at:with:)change nothing.remove(_:)returnsfalse, andremoveAt(_:)andclear()return without a change.move(from:to:)throwsContainerOwnershipError.attachmentFailed. - VM families claim disposal under the lifecycle lock.
MessageHubandNotificationHubuse their own locks.TokenPagedCompositionclaims it on its state queue. MessageHubreleases only its pending transaction queue.- Commands release cancellables and one active task.
NotificationHubcontinuations resume.pending, and post returns.pending.NotificationVMandConfirmationVMrelease a timer, tick, pending subscription, and commands.- The modal type is
BasicModalVM; its continuations resume once. PagedCompositionfinishes its property-change publisher once and releases the source-composite cancellable. Reads remain available.pageSizeandcurrentPageIndexwrites, the four move calls andsetSource(_:)change no state and emit nothing (ADR-0214).TokenPagedCompositionfinishes its collection, property, and command publishers once.BatchUpdateHandleusesdeinitas a safety net.AsyncResourceVM<T>cancels its operation task.AggregateChangeStream.withBatchafter disposal runs the body and emits noBatchevent.
6.8.5.5. Rust¶
PagedComposition::disposedrops the composite-source subscription and stops all publication (ADR-0208). Page reads remain. After disposal,set_page_size,set_current_page_index,next_page,previous_page,move_to_first_page,move_to_previous_page,move_to_next_page,move_to_last_page,set_source,pushandremove_atchange no state and emit nothing (ADR-0254).ModeledCrudCommands::disposedetaches thecurrent_changedtrigger and disposes the confirmation decorators, which completes their error streams. It also disposes the create, update and delete relays that it built, which makes them inert (ADR-0210).NotificationVmandConfirmationVmhave no property-change stream.dispose()disposes their stable dismiss, approve and reject commands, so a kept command clone no longer resolves the hub. It stops the lifespan clock and keepsis_resolved()at its value at disposal. Clones share the disposed state (ADR-0178).- VM families, including modeled composite and forwarding, dispose through
VmNode::dispose. It returnsOk(())on a repeated call with no new work. - A VM sends one
Disposedmessage. It releases children, LIFO owned registrations, and its property-change stream. Illegal lifecycle calls returnVmxError::InvalidLifecycleTransitionfromDisposed(ADR-0203). - Composite and group
add,insert,remove,remove_at,replace,move_itemandclearreturnVmxError::Disposedand make no change (ADR-0187). Compositeset_currentreturnsVmxError::Disposedfor every value,Noneand the child that is already current included. MessageHubclaims disposal under its state mutex. It removes subscribers and drops queued messages instead of completing a stream.SubscriptionandPropertyChangedSubscriptionare the hub subscription handles;Dropis a safety net.ValueStreamandValueSubscriptionare the value streams.RelayCommandandRelayCommandOfrelease command state.AsyncRelayCommand,CompositeCommand,DecoratorCommand, andConfirmationDecoratorCommandclaim disposal through an atomic disposed state.CompositeCommand,DecoratorCommand, andConfirmationDecoratorCommandrelease their inner-hub subscriptions, send one message on their own change hub, and dispose it once. Clones share the disposed state.ConfirmationDecoratorCommandalso disposes its error hub once and releases error subscribers. Confirmation and execution are inert.DerivedProperty,ExpandableState,SearchableState, andDiscriminatorVmdispose their hubs once instead of completing streams.DiscriminatorVmalso disposes its key stream.DerivedPropertyrecompute is inert.TreeSelectiondisposes itscurrent_changedvalue stream once. Clones share the disposed state.FilteredCompositeVmcovers predicate and scored projections. It captures the frozen projection once, releases its source subscription, and completes itschanged()stream.TokenPagedCompositionclaims disposal through a shared disposed gate. Its owned commands enter a terminal disabled state. Late work cannot commit pager state.NotificationHubclaims disposal atomically. Dispose sends no final snapshot onpending_stream()and nopendingmessage onpending_changed(). A laterpending_stream()subscription completes at once with no replay. Waiters readPending; post returns a pending result; resolve cannot re-enqueue (ADR-0197).FormVmenters a terminal inert state. It releases its command gate and approval callbacks; new approval subscriptions are inactive. Disposal calls the completion callback of eachsubscribe_approved_with_completionsubscription once, aftererrors_changedandapprove_errorscomplete. A subscription made after disposal completes at once (ADR-0210).ModalVmsets its result once.AggregateChangeSubscriptiondetaches one output subscription.AggregateChangeStream::batchpanics after disposal.- A
construct(),destruct(), orreconstruct()of a VM during its inline cascade, before it publishesDisposed, returnsVmxError::InvalidLifecycleTransitionfromDisposedand publishes nothing (Ownership Rules).
6.8.6. Practical Teardown Pattern¶
Register every real teardown path and call disposal unconditionally:
page unload ─┐
route switch ├─> root.dispose()
test cleanup ┘
Do not add a second consumer-side disposed flag merely to serialize those paths. Keep ownership explicit: dispose the root and any independently owned services, but do not dispose caller-owned objects through non-owning wrappers.
The owned-resource contract is covered by DISP-007..013 and ADR-0090. Inert
modeled assignment is covered by DISP-014 and ADR-0091.