mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

Ownership and Memory

Mojo is a value-semantics language: an owned value has exactly one holder,

Source: mjdi/docs/ownership-and-memory.md

Mojo is a value-semantics language: an owned value has exactly one holder, and there is no safe way to hand out a second reference to the same instance. mjdi's entire lifetime model follows from that fact. This page explains who owns what, how copies work, when things are destroyed, and why disposal is an explicit, opt-in protocol (InjectableLifecycle).

Who owns what

InstanceOwnerReleased when
A transient resolution (app.resolve[T]() on a transient provider)The callerWhen the caller's variable goes out of scope (Mojo-synthesized deinit).
A singleton's canonical instanceThe container (its registry chain holds it in a slot)app.close() (eager, with pre_destruct for lifecycle conformers) or when the container is destroyed.
A scoped provider's canonical instanceThe Scope valuescope.close_scope() (eager) or when the scope is destroyed.
Copies handed out to consumersThe receiving consumerNormal Mojo scope rules.
A value stored by set_value[T]The container's (or scope's) value slotReplaced by a later set_value; survives close_scope().
The dependency inside an Inject[T] fieldThe owning service instanceWhen the service instance is destroyed.

Two invariants worth memorizing:

  • The compile-time registry never holds instances. Provider metadata lives in types; instances live in descriptor slots owned by the runtime chain of a specific container or scope. Ownership never crosses between the two worlds (Architecture).
  • Everything resolve returns is owned by you. mjdi hands out values — fresh constructions or copies — never borrows of internal state.

Copies: why, and what they cost

Singleton and scoped providers cache one canonical construction and give every consumer a copy. That is forced by value semantics (there is no safe second reference to hand out), and it has three visible consequences:

  1. Cached-lifetime providers require Copyable. This is a compile-time check on the registration: mjdi: singleton class provider 'T' requires the provided type to conform to Copyable because consumers receive copies of the canonical instance (Mojo value semantics). Make the type Copyable or use a transient class provider.
  2. Field mutations never propagate. Two consumers of the same singleton hold independent copies; mutating one's fields changes nothing for the other — or for the canonical instance. Share state explicitly (see below), never through singleton fields.
  3. Dependencies are copied along. A copy of a service copies its Inject fields, so the whole dependency tree of a cached service must be copyable down to the leaves. Inject[T].cloned() exists precisely for this.

Copy constructors and cloned()

A Copyable struct in Mojo 1.2.0 declares the copy constructor:

struct Inventory(Injectable, Copyable):
    var config: Inject[StoreConfig]
    var stock: Int

    def __init__(out self):
        self.config = Inject[StoreConfig]()
        self.stock = 100

    def __init__(out self, *, copy: Self):
        self.config = copy.config.cloned()   # <- the marker copies its dependency
        self.stock = copy.stock

Rules for the copy constructor of an Injectable, Copyable service:

  • Every Inject field is copied with copy.field.cloned(). The marker's cloned() requires the dependency type to be Copyable — that is the mechanism behind "the whole dependency tree must be copyable".
  • Every ordinary field is copied field-by-field.
  • ValueProvider descriptors mirror their slots the same way when a scope is created (mirror_slot_into copies the stored value), so the requirement is uniform: anything reachable from a cached instance must be Copyable.

The error when you forget: registering a non-Copyable type under a cached lifetime fails at compile time (message above); calling cloned() on a non-Copyable dependency is likewise rejected where it is used.

Destruction

Mojo synthesizes destructors from field types, so mjdi adds nothing — and needs nothing:

  • A transient instance is destroyed by the owner's scope exit.
  • A canonical singleton/scoped instance is destroyed when its owner (the container or the scope) is destroyed or, for scopes, eagerly via close_scope() (the slot is cleared; the value is dropped).
  • Value slots deliberately survive close_scope(): they hold configuration, not lifecycle state. They are replaced only by another set_value call. (Provider.slot_clear for value providers is a no-op by design; see mjdi/provider.mojo.)

Linear services are the exception. A linear service opts out of Deinitable, so Mojo never destroys it implicitly — destruction is the service's own explicit destroy(deinit self) method, and mjdi invokes it deterministically at the end of container.resolve[T](/docs/0.10.0/visitor). Where regular services lean on the compiler's synthesized teardown, linear services make release an auditable, mandatory call in exactly one place. See Linear services.

Lifecycle hooks: explicit release, opt-in

mjdi's lifecycle support is opt-in and explicit-release. Services that conform to the InjectableLifecycle trait receive two hooks: post_construct (inside the default Injectable.create, after every Inject field is populated) and pre_destruct (inside the explicit release calls — Scope.close_scope() for a scope's cached instances, Container.close() for the container's cached singletons and cached factory/alias instances — immediately before the slot drops the value). Dropping a container or scope without the explicit release call is still safe: cached instances are destroyed by Mojo's ordinary synthesized teardown, just without the hook.

The design rests on two verified facts: Mojo's synthesized destructors already give deterministic destruction at ownership boundaries, and the verified immutable-view rule for reflected references makes an implicit teardown callback subsystem the wrong shape for value semantics — the trait-declared, compile-time-routed hooks keep the release point in application code where it is auditable. The complete invocation matrix and the exclusions (transient instances, consumer copies, value slots, linear services): Lifecycle hooks.

The practical recipe for resources that need explicit release (connections, files, transactions): scope the resource to a unit of work and release it explicitly at the end of that unit — the same place you call scope.close_scope(), now with pre_destruct firing for lifecycle conformers just before the release.

Sharing observable state

Given copies, how do two services actually share state? Put the state behind an explicitly shared handle and register the handle as a value provider:

struct Stock(Copyable):          # the shared state, as a value
    var items: Int

    def __init__(out self, items: Int):
        self.items = items

    def __init__(out self, *, copy: Self):
        self.items = copy.items

# composition root:
app.register_value[Stock]()      # in the registry
app.set_value[Stock](Stock(100)) # in main()

Services that need the shared state declare Inject[Stock] and receive copies of the stored value. If the value you share is itself a handle to something naturally shared (a connection, a pool, application-owned storage), every copy of the handle still refers to the same underlying resource — that is the honest Mojo pattern: mjdi copies the value; you decide what copies of that value mean.

The one anti-pattern to avoid: making a service singleton because you want shared mutable fields. It does not work (copies), and the failure is silent — the state diverges per consumer. See Patterns → Anti-patterns.