Skip to content

Provider: In Memory

matthew edited this page May 12, 2026 · 1 revision

Provider: In-Memory

An in-process provider for tests and demos. Stores nodes and edges in an InMemoryStore registered under a string name in a process-wide registry. Not for production use — no thread safety on the store, no persistence, no query optimization. Its job is to keep the abstraction honest (a non-Cypher-emitting provider that still satisfies every conformance test) and to make unit testing of consumer code trivial.

Composition root

using Microsoft.Extensions.DependencyInjection;
using OnixLabs.ElementFramework;

services.AddGraphContext<BlogGraphContext>(builder =>
    builder.UseInMemory(databaseName: "tests"));

The databaseName is the key under which the underlying InMemoryStore is registered in InMemoryStoreRegistry. Two contexts pointing at the same database name share the same store; pointing at different names gives you isolation.

With logger factory:

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

Test reset

Because the registry is process-wide, integration tests that share an in-memory database need a way to reset state between runs. InMemoryStoreRegistry exposes a public reset hook:

[Fact]
public void SomeTest()
{
    InMemoryStoreRegistry.Reset("tests");   // clear the store for this database name
    // … now run the test against a clean slate
}

For tests that want a fresh store per test, use a unique database name per test (e.g., Guid.NewGuid().ToString()).

Storage: InMemoryStore, InMemoryStoreRegistry, InMemoryEdge

The store keeps two collections per node label and two per relationship type:

  • Dictionary<object, object> keyed by node key — the node entities themselves.
  • List<InMemoryEdge> per relationship type — edges as triples of (startKey, endKey, payload).

InMemoryEdge carries the start and end keys plus the edge's own property values. Lookups walk the relevant list.

Not thread-safe. Concurrent contexts pointing at the same database name will race. Acceptable trade-off for the test-only target audience; flagged in xmldoc.

Op-coded statements: InMemoryStatementEmitter, InMemoryRawStatementExecutor

Unlike Cypher / AQL providers, the in-memory provider has no real query language. Instead, the emitter encodes each operation as a JSON op-code:

{ "op": "addNode", "label": "Author", "key": "...", "props": { ... } }
{ "op": "findById", "label": "Author", "key": "..." }
{ "op": "connect", "type": "Wrote", "startKey": "...", "endKey": "...", "props": { ... } }
{ "op": "traverse", "kind": "Match", "segments": [...], "predicates": [...] }

InMemoryRawStatementExecutor reads the op-code and dispatches to the corresponding InMemoryStore operation directly. There's no parsing, no syntax tree — the statement is an op-code.

RawStatement.Execute accepts the same op-codes, so the four raw-statement conformance tests that send Cypher into other providers are skipped here — bare openCypher isn't a valid op-code.

Materialization: InMemoryResultMaterializer

The store returns CLR entities directly (no serialization round-trip), so materialization is essentially a copy: walk the property metadata, copy each property value from the source entity to a fresh instance. No JSON parsing, no type coercion — values are already CLR-shaped.

Transactions: snapshot-based

InMemoryGraphTransactionOpener.Open() creates a deep snapshot of the store and wraps it in an InMemoryGraphTransaction. Writes during the transaction mutate the snapshot. On commit, the snapshot replaces the store; on rollback or dispose without terminal, the snapshot is discarded.

This gives true rollback semantics — failed transactions leave the store untouched — and matches the conformance suite's expectations for transactional behaviour. It's also why the in-memory provider's "not thread-safe" applies at the store level: concurrent transactions on the same database name would race on the snapshot pointer.

Traversal: InMemoryTraversalTranslator

Walks the pattern segments directly against the store:

  1. For the start node segment, fetch every entity in the matching collection.
  2. For each subsequent (relationship, end-node) pair, find every edge of the matching type departing from the current node in the matching direction, then yield the end-node entity.
  3. Apply predicates by evaluating the predicate tree against each candidate (compiled into a Func<TBindings, bool> once per traversal).
  4. Apply ordering, skip, take.
  5. Materialize the return alias.

The translator is the most straightforward implementation of ITraversalTranslator in the codebase — no SQL, no Cypher, no AQL — and serves as a reference for what the AST is asking of every provider.

Conformance

All conformance tests pass except the four raw-statement Cypher tests (which would need a Cypher parser to interpret).

Full example

using Microsoft.Extensions.DependencyInjection;
using OnixLabs.ElementFramework;

ServiceCollection services = new();
services.AddGraphContext<BlogGraphContext>(builder =>
    builder.UseInMemory("tests"));

await using ServiceProvider provider = services.BuildServiceProvider();
using IServiceScope scope = provider.CreateScope();
BlogGraphContext context = scope.ServiceProvider.GetRequiredService<BlogGraphContext>();

Author ada = new() { Id = Guid.NewGuid(), Name = "Ada", JoinedAt = DateTimeOffset.UtcNow };
context.Nodes<Author>().Add(ada);
await context.SaveChangesAsync();

Author? loaded = context.Nodes<Author>().FindById(ada.Id);
Console.WriteLine($"Loaded: {loaded?.Name}");

When to use it

  • Unit tests of consumer code that needs a real GraphContext without spinning up a database.
  • Demos where Docker overhead would slow the feedback loop.
  • Conformance regression testing — the same conformance tests run against four providers, and the in-memory one catches abstraction-layer regressions in seconds without containers.

When NOT to use it: any code path that runs in production. The lack of thread safety, the unbounded process-wide registry, and the absence of persistence are all explicit trade-offs that don't survive past the test/demo boundary.