Skip to content

6.2.5. Composite Family

6.2.5.1. When To Use It

Use CompositeVM<VM> when the parent owns an ordered homogeneous child list and one child may be current. Tabs, note lists, result lists, and other "collection plus selection" workflows belong here.

Use the modeled composite when children are projected from models during construction instead of being provided directly.

Composite Family Deep Dive

HTML · SVG · PNG

6.2.5.2. Shape And Ownership

CompositeVM adds one core concept on top of a collection container:

  • Current may be one child or null

Everything else follows from that contract: guarded selection helpers, foreground updates of IsCurrent, and optional builder hooks for initial selection and current-changed callbacks.

Composite implements the selectable extension of the shared VM Collection Contract. Its atomic move keeps the identical child, parent, lifecycle, subscriptions, and Current reference.

Every child has one authoritative owning parent. Adding or inserting a child that belongs to another mutable composite or group atomically removes it from the old parent first. Duplicate identity and ancestor cycles are rejected. If the destination attach fails, old membership, index, and selection are restored without publishing a partial transfer.

The destination and staged old parent stay isolated until commit or rollback. Structural mutation attempted re-entrantly from an auto-construction or population hook is rejected before it can invalidate rollback state. A structural change from another thread during the transaction fails at once in the same way. Only disposal waits for the transaction to end (ADR-0187). Selection validation and assignment share the membership gate, and deferred selection rechecks that the candidate is still a child.

Reverse-order bulk transfers use deterministic reservation ordering. The transaction rechecks destination disposal after auto-construction before it commits membership. If user lifecycle code fails during compensation, VMx surfaces that rollback failure instead of claiming that lifecycle state was restored exactly (ADR-0118).

When a failed add, insert, index replacement or population also fails its lifecycle compensation, the reported failure gives access to the original operation failure and to the first compensation failure (ADR-0218):

Flavor Reported failure
C# AggregateException. InnerExceptions[0] is the original failure, and the compensation failures follow in order.
Python the first compensation failure, raised from the original failure (__cause__).
TypeScript ContainerRollbackError, with the original failure as cause and the compensation failure as rollbackError.
Swift ContainerOwnershipError.attachmentFailed with a ContainerRollbackError payload, which has originalError and compensationError.
Rust VmxError::ContainerRollback { original, compensation }.

Old-parent disposal requested by an attachment hook waits for commit or rollback. A committed transfer publishes old removal and new addition before a throwing/result-based flavor surfaces any deferred disposal failure. When attachment already failed, that earlier error remains primary after rollback and disposal complete. A lazy population that already committed stays materialized rather than evaluating its factory again (ADR-0122).

6.2.5.3. Lifecycle And Messaging

The composite owns both child lifecycle and selection messaging:

  • construct() waits for every child before the composite reports constructed. It counts members only: a child removed during the walk does not roll the composite back (spec/06 §5.1, ADR-0186)
  • destruct() clears Current before destructing children. The clear opens no membership transaction, never waits and is never refused, so it also works while another thread adds a child or disposal is pending (spec/06 §5, ADR-0173)
  • the default destruct and dispose order is unspecified (spec 02 §6). Only DestructOrder(ChildOrder.Reverse) is guaranteed: it walks the children last child first, so a child that depends on an earlier sibling is torn down before it (ADR-0161). Construct order does not change, and every child is still disposed before the composite, unless the dispose is foreign (spec 02 §7)
  • Current changes publish the parent Current property and the affected children's IsCurrent
  • disposal requested by a current-changed callback is deferred until the selection notification finishes and does not deadlock the callback
  • AsyncSelection(true) routes selection work through the foreground dispatcher. The delivery checks the selection again and drops it silently when it is no longer valid
  • a non-batched move emits one move event with both indices; a batched move is represented by the outer reset
  • each local collection change is followed by one CollectionChangedMessage on the composite's hub, and a batch that changes the collection sends one Reset (ADR-0142)

Rust background-child settling follows the shared container rule in ViewModel Families.

6.2.5.3.1. Selection And Membership Transactions

Selection never opens, joins or waits for a membership transaction, in any flavor (spec/06 §4.3, ADR-0173). Each selection validates and commits under the composite's own locks and then publishes:

  • Another thread's add or removal never blocks a selection. A construct hook or another thread can select while an add is still running, and the selection neither fails nor waits.
  • A child is selectable once its add admits it. Selecting a child that an add or a population has attached but not admitted raises the non-member error. A CollectionChanged subscriber can select the child that was just added. An add that moves a child from another composite admits it after that composite's removal commits, so the child's IsCurrent flag always matches the new parent's Current.
  • The adding thread cannot select before its add commits. A hook on the thread that runs the add gets the "membership transaction in progress" error, also for Current = null. A failed add therefore leaves Current unchanged.
  • A disposing composite refuses a non-null selection. Setting Current to null and deselecting stay legal.
  • Publications can interleave. Two threads that select at the same time can publish their changes in either order.

6.2.5.3.2. Restoring The Current Child

The Current(selector) hook runs during every construct phase, including the construct phase of reconstruct() (spec/06 §3.2, ADR-0158). Destruct first sets Current to null and reports null to OnCurrentChanged. To restore the last selection, record only the non-null values and return the last one from the selector:

let lastCurrent: ComponentVM | null = null;
const tabs = CompositeVM.builder<ComponentVM>()
  .name("tabs")
  .services(hub, dispatcher)
  .children(() => [home, settings])
  // Destruct reports null. Record only a real selection.
  .onCurrentChanged((tab) => {
    if (tab !== null) lastCurrent = tab;
  })
  // Runs on every construct, including reconstruct().
  .current(() => lastCurrent)
  .build();
  • Record only a real selection. If the callback also records the null from destruct, the selector returns null, and no child is restored.
  • A removed child is not restored. If the composite no longer contains the recorded child, the selector's result is a silent no-op, and Current stays null.
  • Only committed children are selected. Another thread's membership transaction never makes the assignment raise or wait. A child that another add has attached but not yet admitted is not contained yet. The assignment is also a no-op while the composite is disposing (spec/06 §3.2, ADR-0165, ADR-0173). Every flavor follows these rules, and the assignment is synchronous also with AsyncSelection(true).

6.2.5.4. Cross-Language Surface

Concept C# Python TypeScript Swift Rust
Type CompositeVM<VM> CompositeVM[VM] CompositeVM<VM> CompositeVM<VM> CompositeVm<VM>
Modeled type CompositeVMOfM<M, VM> CompositeVMOf[M, VM] CompositeVMOf<M, VM> CompositeVMOf<M, VM> ModeledCompositeVm<M, VM>
Selection slot Current current current current current()
Initial selector hook Current(selector) current(selector) current(selector) current(selector) current(selector)
Reverse teardown DestructOrder(ChildOrder.Reverse) destruct_order(ChildOrder.REVERSE) destructOrder("reverse") destructOrder(.reverse) destruct_order(ChildOrder::Reverse)

6.2.5.5. Example

var tabs = CompositeVM<ComponentVM<TabModel>>.Builder()
    .Name("tab-bar")
    .Services(hub, dispatcher)
    .Children(() => new[] { home, settings })
    .Build();
tabs = (
    CompositeVM[ComponentVMOf[TabModel]]
    .builder()
    .name("tab-bar")
    .services(hub, dispatcher)
    .children(lambda: [home, settings])
    .build()
)
const tabs = CompositeVM.builder<ComponentVMOf<TabModel>>()
  .name("tab-bar")
  .services(hub, dispatcher)
  .children(() => [home, settings])
  .build();
let tabs = try CompositeVM<ComponentVMOf<TabModel>>.builder()
    .name("tab-bar")
    .services(hub: hub, dispatcher: dispatcher)
    .children { [home, settings] }
    .build()
let tabs = CompositeVm::<ComponentVm<TabModel>>::builder()
    .name("tab-bar")
    .services(hub, dispatcher)
    .children(move || vec![home.clone(), settings.clone()])
    .build()?;

Rust ships both CompositeVm and ModeledCompositeVm. A Rust FilteredCompositeVm takes its cursor policy at construction (with_cursor_policy, scored_with_cursor_policy) and publishes changed() (ADR-0207).

6.2.5.6. Common Pitfalls

  • Using a composite for recursive trees. HierarchicalVM carries the tree semantics directly.
  • Forgetting that Current must always be a contained child or null.
  • Treating one child identity as simultaneous membership in multiple containers. Mutable attachment transfers ownership; aggregate slots must be released by replacing or rebuilding the aggregate instead.
  • Assuming add-after-construct auto-constructs by default. It does not unless AutoConstructOnAdd(true) is enabled.
  • Updating selection predicates without wiring current-changed triggers into commands that depend on selection.