Skip to content

Architecture: Implementation

matthew edited this page May 12, 2026 · 1 revision

Architecture: Implementation

The internals that sit between the consumer surface and the provider contract — change tracker, transaction factory, lifecycles, diagnostics. None of this is provider-specific; every provider sees the same flow.

Change tracker

ChangeTracker is the heart of the framework. It owns three pieces of state per context instance:

  • Identity map — a Dictionary<(Type, object key), object> that tracks every entity the context has seen (by Add, FindById, traversal materialization, or RawStatement.Execute result). Used to short-circuit FindById and to keep entities reference-stable within a context's lifetime.
  • Pending queue — a List<Func<IStatementEmitter, IGraphModel, DataStatement>> accumulating closures over the operations queued since the last flush. Closures capture the entity reference at track time so the emitter sees current property values at flush time, not stale snapshots.
  • Ambient routing flag — derived from IGraphTransactionOpener.Active. Decides whether Flush opens an auto-transaction or enlists on the existing one.

Flush semantics

Flush (and FlushAsync):

  1. Snapshot the pending queue.
  2. If opener.Active is non-null, route through the ambient transaction. Otherwise, open an auto-transaction internally — but not through GraphTransactionFactory. This bypass is deliberate: auto-flush rollback must preserve the pending queue so the consumer can retry after a corrected error, whereas GraphTransactionFactory-opened rollback clears it.
  3. Iterate the snapshot, emit each op via IStatementEmitter, execute each via IRawStatementExecutor.
  4. On success: clear the pending queue.
  5. On failure: leave the pending queue intact (so a retry can replay).

The identity map is not rolled back on failure. TrackRemove updates the map at track time, so after a failed flush the map can claim a node is gone while the database still has it. This is a documented sharp edge — see the gotchas section of agents.md.

Diagnostics

Every flush emits an ElementFramework.SaveChanges span tagged with the operation count and the routing mode (ambient / auto), plus increments to the elementframework.savechanges.flushes and elementframework.savechanges.operations counters. Empty flushes tick the counter with outcome=noop but do not start a span.

Transaction factory and rollback semantics

GraphTransactionFactory wraps IGraphTransactionOpener and adds rollback-aware change-tracker reset:

  • Successful commit → identity map and pending queue are kept (entities tracked are still tracked; the consumer continues working with the same context).
  • Rollback (explicit or via dispose) → the change tracker is reset: identity map cleared, pending queue cleared. The post-rollback context behaves as if nothing happened since the transaction began.

This is the difference between auto-transactions (no tracker reset on failure — pending queue preserved for retry) and explicit transactions (tracker reset on failure — explicit retry is the consumer's job).

The factory exposes its active transaction wrapped in RollbackAwareGraphTransaction, which dispatches to the underlying IGraphTransaction while applying the reset on the rollback path.

Diagnostics:

  • ElementFramework.BeginTransaction span when the factory opens.
  • ElementFramework.Transaction.Commit / .Rollback spans on terminal.
  • elementframework.transactions.terminals counter ticks with outcome=committed / rolledback / commit_failed / rollback_failed / disposed_without_terminal.

The bypass mentioned above — auto-transactions go through the opener directly, not the factory — means the BeginTransaction/Commit spans do not appear on SaveChanges-only calls. Only consumer-initiated BeginTransaction calls show the full hierarchy.

Model caching: ModelSource

ModelSource is a process-wide ConcurrentDictionary<Type, Lazy<GraphModel>> keyed by GraphContext CLR type. The first time a context of type T is constructed, OnModelCreating runs, the resulting model is validated, frozen, and cached. Every subsequent T instance gets the cached model.

Implications:

  • OnModelCreating must be pure with respect to the type system. Non-pure logic (e.g., reading config, capturing closures over instance state) produces a model that won't match later instances.
  • Tests that swap context implementations at runtime see the first model registered, not the most recent one. The conformance suite sidesteps this by running each provider's test class with its own context subclass.

DI registration: AddGraphContext<T>

The composition root:

services.AddGraphContext<BlogGraphContext>(builder =>
    builder.UseNeo4j(...));

Internally:

  1. The action runs against a GraphContextOptionsBuilder that accumulates provider services (IStatementEmitter, IResultMaterializer, IRawStatementExecutor, IGraphTransactionOpener, ITraversalTranslator) and an optional ILoggerFactory.
  2. The builder produces a GraphContextOptions carrying those services.
  3. services.AddScoped<TContext>(sp => new TContext(options)) is registered — the context is scoped by default. Provider services are bundled inside the options and constructed once during registration; the scoping is on the context itself.

There's an SP-aware overload that lets the provider extension method resolve services from the container (e.g., ILoggerFactory) instead of having the consumer pass them explicitly:

services.AddGraphContext<BlogGraphContext>((sp, builder) =>
    builder
        .UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
        .UseNeo4j(...));

UseLoggerFactory must be called before the provider's Use* extension — providers read the factory at composition time to build their own typed loggers.

Logging conventions

The framework consumes ILoggerFactory and writes diagnostic events at consistent levels across every component:

  • Every statement at Debug, including parameter count (never values).
  • Transaction open / commit / rollback / best-effort-rollback-on-dispose at Information.
  • Previously-swallowed dispose-path exceptions at Warning (the dispose contract forbids letting them out, but silence isn't free either).
  • ChangeTracker.Flush start/end at Debug. Rollback events at Warning.

To inject a logger factory from a host, use the SP-aware AddGraphContext overload and call UseLoggerFactory before the provider's Use* extension.

Diagnostics surface (OpenTelemetry)

The framework emits OpenTelemetry-compatible spans and counters through System.Diagnostics.ActivitySource and System.Diagnostics.Metrics.Meter instruments. No dependency on the OpenTelemetry SDK — consumers wire in their own exporter:

services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddSource("OnixLabs.ElementFramework")
        .AddSource("OnixLabs.ElementFramework.Neo4j")    // or .AGE, .Arango
        .AddOtlpExporter())
    .WithMetrics(metrics => metrics
        .AddMeter("OnixLabs.ElementFramework")
        .AddMeter("OnixLabs.ElementFramework.Neo4j")
        .AddOtlpExporter());

Span inventory

Span Kind Tags
ElementFramework.SaveChanges Internal elementframework.operation.count, elementframework.transaction.mode, exception.type (on error)
ElementFramework.BeginTransaction Internal exception.type (on error)
ElementFramework.Transaction.Commit Internal exception.type (on error)
ElementFramework.Transaction.Rollback Internal exception.type (on error)
Neo4j.ExecuteStatement Client db.system=neo4j, parameter count, transaction mode
Neo4j.TranslateTraversal Internal db.system=neo4j, traversal kind / segment count / predicate count / return alias
AGE.ExecuteStatement / AGE.TranslateTraversal … as above with db.system=postgresql
Arango.ExecuteStatement / Arango.TranslateTraversal … as above with db.system=arangodb

ExecuteStatement covers only the open-cursor / open-reader phase. Streaming continuation is intentionally outside the span — the driver's own ActivitySource (where one exists) emits the wire-layer fetches, and keeping our span tight to the actual round-trip avoids spans that hang for the duration of a long enumeration.

Counter inventory

Meter Counter Tags
Framework elementframework.savechanges.flushes outcome (success / failure / noop), transaction mode
Framework elementframework.savechanges.operations transaction mode
Framework elementframework.transactions.terminals outcome (committed / rolledback / commit_failed / rollback_failed / disposed_without_terminal)
Per provider elementframework.<provider>.statements transaction mode, outcome

PII discipline

Spans and counters attach only structural metadata — counts, kinds, modes, alias names, outcome tags. Never parameter values, never full statement bodies, never property values returned from the database. The xmldoc on every *Diagnostics class restates this discipline. New tags added to existing spans should be reviewed against it.

Lifecycle: SaveChanges from end to end

To make the flow concrete, here's what happens on a single SaveChangesAsync call against a Neo4j-backed context with three pending operations:

  1. Consumer calls context.SaveChangesAsync().
  2. ChangeTracker.FlushAsync starts an ElementFramework.SaveChanges span.
  3. The tracker snapshots the pending queue (three closures).
  4. opener.Active is null → auto-transaction path. The tracker calls opener.OpenAsync directly (not through GraphTransactionFactory).
  5. Neo4jGraphTransactionOpener.OpenAsync borrows an IAsyncSession from the cached driver and begins an IAsyncTransaction. The active slot is set.
  6. The tracker iterates the snapshot:
    1. For each closure, call emitter.EmitAdd<T>(model, entity) → DataStatement.
    2. executor.ExecuteAsync(statement.Statement, statement.Parameters) starts a Neo4j.ExecuteStatement span (tagged mode=ambient), runs the statement, ticks elementframework.neo4j.statements{outcome=success, mode=ambient}, ends the span.
    3. On any failure, the executor wraps the driver exception as RawStatementException, the tracker propagates, the auto-transaction rolls back, the pending queue is preserved.
  7. All three succeed. The tracker commits the transaction via IGraphTransaction.CommitAsync. Pending queue is cleared.
  8. The SaveChanges span ends with status Ok, elementframework.savechanges.flushes{outcome=success} ticks.

No BeginTransaction / Commit spans appear in this flow because the auto-transaction bypassed GraphTransactionFactory. An explicit BeginTransactionAsync + SaveChangesAsync + CommitAsync cycle would show the full hierarchy.