Repository navigation
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.
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 (byAdd,FindById, traversal materialization, orRawStatement.Executeresult). Used to short-circuitFindByIdand 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 whetherFlushopens an auto-transaction or enlists on the existing one.
Flush (and FlushAsync):
- Snapshot the pending queue.
- If
opener.Activeis non-null, route through the ambient transaction. Otherwise, open an auto-transaction internally — but not throughGraphTransactionFactory. This bypass is deliberate: auto-flush rollback must preserve the pending queue so the consumer can retry after a corrected error, whereasGraphTransactionFactory-opened rollback clears it. - Iterate the snapshot, emit each op via
IStatementEmitter, execute each viaIRawStatementExecutor. - On success: clear the pending queue.
- 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.
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.
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.BeginTransactionspan when the factory opens. -
ElementFramework.Transaction.Commit/.Rollbackspans on terminal. -
elementframework.transactions.terminalscounter ticks withoutcome=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.
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:
-
OnModelCreatingmust 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.
The composition root:
services.AddGraphContext<BlogGraphContext>(builder =>
builder.UseNeo4j(...));Internally:
- The action runs against a
GraphContextOptionsBuilderthat accumulates provider services (IStatementEmitter,IResultMaterializer,IRawStatementExecutor,IGraphTransactionOpener,ITraversalTranslator) and an optionalILoggerFactory. - The builder produces a
GraphContextOptionscarrying those services. -
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.
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.Flushstart/end atDebug. Rollback events atWarning.
To inject a logger factory from a host, use the SP-aware AddGraphContext overload and call UseLoggerFactory before the provider's Use* extension.
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 | 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.
| 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
|
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.
To make the flow concrete, here's what happens on a single SaveChangesAsync call against a Neo4j-backed context with three pending operations:
- Consumer calls
context.SaveChangesAsync(). -
ChangeTracker.FlushAsyncstarts anElementFramework.SaveChangesspan. - The tracker snapshots the pending queue (three closures).
-
opener.Activeis null → auto-transaction path. The tracker callsopener.OpenAsyncdirectly (not throughGraphTransactionFactory). -
Neo4jGraphTransactionOpener.OpenAsyncborrows anIAsyncSessionfrom the cached driver and begins anIAsyncTransaction. The active slot is set. - The tracker iterates the snapshot:
- For each closure, call
emitter.EmitAdd<T>(model, entity)→DataStatement. -
executor.ExecuteAsync(statement.Statement, statement.Parameters)starts aNeo4j.ExecuteStatementspan (taggedmode=ambient), runs the statement, tickselementframework.neo4j.statements{outcome=success, mode=ambient}, ends the span. - On any failure, the executor wraps the driver exception as
RawStatementException, the tracker propagates, the auto-transaction rolls back, the pending queue is preserved.
- For each closure, call
- All three succeed. The tracker commits the transaction via
IGraphTransaction.CommitAsync. Pending queue is cleared. - The
SaveChangesspan 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.