mjdi

Search documentation

Search the mjdi v0.10.0 documentation

mjdi docsv0.10.0latest

mjdi Architecture

This document describes mjdi's components, the compile-time/runtime split

Source: mjdi/docs/architecture.md

This document describes mjdi's components, the compile-time/runtime split that defines the library, and the rationale for the shape of the design on Mojo 1.2.0. Every claim about compiler behavior is backed by an experiment in experiments/ and a row in docs/technical-investigation.md.

The defining separation

COMPILE TIME                                   RUNTIME
----------------------------------------      ----------------------------------------
Provider registration (type-level chain)      Object construction
Type metadata & provider descriptors          Factory execution
Dependency discovery (reflection)             Singleton/scoped instance caching
Dependency graph construction                 Transient instance creation
Static validation (missing/cycles/scopes)     Value-provider slots
Resolution specialization                     Ownership of returned values

The compile-time registry stores provider metadata and type information; it never stores service instances. The runtime container stores instances; it never discovers provider metadata that can be resolved at compile time.

Components

mjdi/
├── __init__.mojo              Public API surface
├── errors.mojo                Diagnostic message builders (comptime strings)
├── annotations.mojo           mjdi_linear annotation value + is_linear query
├── provider.mojo              Scopes, kinds, origins, descriptors, resolver
│                              and graph-rendering contracts
├── inject.mojo                Inject[T], ResolvableField, cycle walk helpers
├── dependency_resolver.mojo   Public re-export of DependencyResolver
├── dependency_scanner.mojo    Reflection-based field discovery & population
├── injectable.mojo            Injectable trait + default construction
├── lifecycle.mojo             InjectableLifecycle hooks (post_construct / pre_destruct)
├── linear.mojo                LinearService contract + LinearProvider descriptor
├── registry.mojo              Immutable type-level registry chain + runtime slots
│                              + the override family + graph chain dispatch
├── dependency_graph.mojo      Compile-time validation walks
├── observability.mojo         TraceLog / TraceEvent / CacheStats / RuntimeValidation
├── graph.mojo                 GraphDocRenderer: graph_json / graph_dot /
│                              explain_resolution (all comptime)
├── guards.mojo                with_scope / with_container, ScopeGuard / ContainerGuard
├── testing.mojo               The mjdi.testing assertion family
├── container.mojo             Container[registry, traced, stats, guard] and Scope

Module dependency direction (acyclic):

errors / annotations / observability (leaves)
        <- provider <- inject <- dependency_scanner <- injectable
        <- lifecycle <- provider
        <- linear <- registry <- dependency_graph <- container
        <- container <- guards <- testing
        <- registry <- graph (comptime introspection over the chain)

provider.mojo hosts the DependencyResolver trait (rather than a separate module) because provider descriptors must reference it without creating an import cycle; dependency_resolver.mojo is its public home. The graph-walk helpers for cycle detection live in inject.mojo for the same reason: the recursion is dispatched through the ResolvableField static surface that is declared there. The lifecycle contract lives in its own leaf module, lifecycle.mojo: InjectableLifecycle declares the post_construct / pre_destruct hooks the provider descriptors and the default create invoke behind compile-time conforms_to gates, with no import cycle (the trait has no dependencies). Ownership itself is still fully specified by Mojo's move/copy semantics; the hooks fire on the explicit release paths, documented in docs/lifecycle.md and docs/known-limitations.md.

Registry: an immutable type-level linked list

Registry() is the empty registry. Every register* call returns a new registry whose type parameters encode the accumulated provider set:

Registry -> ProviderRegistry[ClassProvider[UserRepository, transient], Registry]
         -> ProviderRegistry[ClassProvider[Logger, transient], ...]
         -> ...

There is no mutable global state: composing a registry never mutates anything, and every intermediate registry remains valid. Because the provider set lives in the type, provider lookup, duplicate detection, graph validation, and runtime slot access are all specialized per registry.

Each node of the chain is both compile-time metadata and runtime state:

  • the head descriptor (ClassProvider[T, scope], ValueProvider[T], FactoryProvider[T, factory], AliasProvider[From, To]) declares what it provides and how it supplies it,
  • descriptor instances carry the runtime slots: value-provider slots and singleton/scoped caches are Optional[T] fields inside the descriptors.

A Container[registry] owns one runtime instance of the whole chain (var _registry: Self.registry), so container state is exactly one registry-chain instance per container (and one per scope).

Descriptor dispatch

The container never matches on descriptor types directly. Each descriptor conforms to ProviderSpec, whose static surface (provides, kind_of, scope_of, supply_as) is dispatched through trait-static calls on generic type parameters — the mechanics verified in experiments/exp3_registry.mojo. This is also how mjdi avoids ever needing to extract generic arguments from a descriptor: every descriptor knows its own T through Self.T, and every query is a method call on the descriptor itself.

Dependency discovery: marker-trait dispatch, not unwrapping

Inject[T] conforms to ResolvableField, a marker trait with one job per field type: produce a fully populated wrapper (resolve_field) and answer validation queries (is_provided_in, dependency_scope_in, cycle_path_from). The scanner (dependency_scanner.mojo) reflects over a service's fields, checks conforms_to(FT, ResolvableField) per field, and delegates; it never inspects Inject's storage layout, and never extracts T by descending into Optional/Variant internals (which would couple it to stdlib implementation details). This design is justified in docs/technical-investigation.md (design note 1).

Construction: two-phase

Automatic construction is two-phase:

  1. Self() — the service is default-constructed (Injectable extends Defaultable; Inject is always default-constructible regardless of the dependency type).
  2. The scanner resolves each marker field through the active resolver and writes the populated wrapper back via reflect[T].field_ref[i], with rebind applied to the destination reference.

This is the only safe reflective construction on Mojo 1.2.0: arbitrary- argument reflective construction (tuple-splat into a fixed-arity callee, pack concatenation, passing __init__ as a function value) is rejected by the compiler, and field_ref on an uninitialized out parameter is rejected. See experiments/exp4_construction.mojo and investigation findings 19–22.

Validation

Container[registry].__init__ runs validate_registry[registry]() at elaboration time — before any application code executes. The walk visits every registered provider and checks:

  • missing providers — every Inject[D] field of every class-provided service must have a provider for D (check_missing_providers);
  • duplicate registrations — a class/value/factory provider whose service is already provided by a later node in the chain is rejected (check_unique_against);
  • lifetime relationships — a singleton service must not depend on a scoped provider (check_scope_rules);
  • alias validity — the target must be registered as a class provider, the aliased type must be Injectable, and binding is checked at validation time (alias cycles are impossible by construction: aliases bind to class providers only);
  • resolution-time rejections — resolving a scoped provider outside a scope raises at the point of resolution (the same specialization serves scopes, where scoped resolution is legal).

Some conditions are runtime by nature and are documented as such: a missing value-provider value, and factory failures. Compile-time structural validation and runtime provider execution are clearly separated, per the product requirements.

Ownership and lifetimes

Mojo is a value-semantics language: an owned value has exactly one holder. mjdi's lifetime model is therefore:

  • Transient — a fresh instance per resolution; the caller owns it.
  • Singleton / scoped — the container (or scope) owns one canonical instance in its slot; consumers receive copies, which requires the provided type to be Copyable. The canonical instance is released when the container is destroyed or Scope.close_scope() is called (value slots are configuration and are mirrored into scopes at creation; they survive close_scope).
  • Returned values are owned by the caller. Inject[T] fields own their resolved dependency (a copy for singleton/scoped providers, a fresh instance for transient ones).

The compile-time registry never holds instances; the runtime chain does. Ownership never crosses between the two.

How the P0 hardening layer integrates (0.9.0)

The P0 work adds a trust/readiness layer on top of the architecture above without touching its shape:

  • Release metadata (P0-01) is a repository-level concern: release/manifest.json is the canonical identity; the validator (scripts/validate_metadata.py) treats every synced location as derived or validated state. The runtime library is untouched.
  • The compatibility matrix (P0-02) is documentation-plus-CI: the evidence tiers live in the manifest and docs/compiler-compatibility.md; the CI matrix executes the authoritative inventory per platform.
  • Lifecycle safety diagnostics (P0-03) follow the established specialization pattern: debug_tracking is a defaulted container/scope parameter; the DebugLog (in observability.mojo) is a pull-model sibling of TraceLog/CacheStats; the destructor diagnostics reuse the existing collect_cached_services chain walk rather than adding a new inventory mechanism.
  • Close semantics (P0-04) and the failure policy (P0-05) are documentation and test-pinning of the existing slot-based release path (slot_clear → pre_destruct → drop); the only runtime additions are the informational _closed flag and its accessors. The exactly-once guarantee was already a property of the Optional[T] slots; it is now explicit, documented, and pinned.
  • The diagnostic contract (P0-06) centralizes what was previously implicit: message builders across five modules now embed pinned IDs, the generator scans the whole library, and the catalog is the single machine-readable registry — the same file the IDE tooling consumes.
  • Runtime error consistency (P0-08) adds one wrapper (_run_factory in provider.mojo) on the factory path; the other three categories were message-content upgrades within the existing raise/abort paths.
  • The alias and scope semantics work (P0-09/P0-10) changed no dispatch code: they pin the existing head-first chain dispatch and per-context slot caching with dedicated tests and documentation.
  • The inventory (P0-07) and the release gate close the loop: every suite figure in the documentation is derived from the runners, and scripts/release_gate.sh runs the whole verification set in one command.

The layering principle is unchanged: compile-time-first validation remains the primary mechanism; the runtime additions are observation, not enforcement — and every new runtime surface is a defaulted, opt-in specialization that leaves the default behavior byte-identical.