AI Wikis / Agentic Web

Deterministic Experience-Memory Graph Edit-Path Subsystem: Architectural Design and Implementation

Report summary

The evolution of autonomous computational agents has rapidly advanced the frontier of sequential decision-making. However, in complex, long-horizon environments, these agents remain highly susceptible to compounding errors and catastrophic execution failures1. The prevailing methodology for error re

Status
Research archive item
Category
AI Wikis / Agentic Web
Length
4,602 words
Reading time
21 minutes
Report type
architecture

Key topics

  • AI Wikis / Agentic Web
  • AI Wikis
  • Agentic Web
  • AI
  • .NET
  • SQL
  • Runtime
  • Semantic Systems
  • Research Archive

Research provenance

Archive status
Research archive item
Content identity
sha256:60809d61f520a1ed15f64a8df637038e3b2ac7f3b09e80bd5a59d6f7216211f7

For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.

This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.

Full report

On this page

The evolution of autonomous computational agents has rapidly advanced the frontier of sequential decision-making. However, in complex, long-horizon environments, these agents remain highly susceptible to compounding errors and catastrophic execution failures1. The prevailing methodology for error recovery relies almost exclusively on online, prompt-based self-reflection loops. This approach is computationally expensive, introduces substantial latency, suffers from algorithmic brittleness, and typically yields myopic, task-specific corrections that fail to generalize1. Addressing these fundamental bottlenecks requires a paradigm shift from stochastic runtime reflection to deterministic offline computation. This architectural treatise details the design and production-grade implementation of a deterministic graph edit-path subsystem, which forms the computational core of an Experience Memory Graph (EMG) framework3. By reformulating agent failure recovery as a structural graph matching problem, the subsystem offline-aligns failed exploration trajectories with successful expert trajectories3. This alignment extracts actionable correction plans—represented as optimal graph edit paths—that dictate precisely which actions an agent must add, delete, or relabel under specific environmental observations to transform a failed workflow into a successful one1. The emitted sequence constitutes a reusable, one-shot correction plan, completely bypassing the need for test-time trial-and-error4.

Theoretical Foundations of Structural Memory Alignment

Traditional agent memory systems operate as passive text buffers or vector stores, fundamentally lacking the capacity to model multi-hop dependencies or causal hierarchies6. Graph-based agent memory structures these interactions chronologically and causally, representing states and actions as interconnected topologies8. Within the EMG framework, interaction logs are serialized into Action Decision Graphs (ADGs), where nodes represent normalized actions and edges denote the environmental observations precipitating those actions4. Computing the minimum transformation between a failed ADG and a successful ADG requires calculating the Graph Edit Distance (GED). Classical exact GED computation is NP-hard, relying on combinatorial A\* search heuristics that scale exponentially and are unsuited for deep execution trajectories9. To achieve scalable algorithmic exactness, the subsystem leverages optimal transport (OT) theory, specifically utilizing the Fused Gromov-Wasserstein (FGW) distance11. The FGW distance provides a unified metric that jointly minimizes feature mismatch (Wasserstein distance) and structural distortion (Gromov-Wasserstein distance) via a single probabilistic coupling matrix13. Recent mathematical advancements, such as the FGWAlign algorithm, demonstrate that projecting this probabilistic transport plan back into discrete node alignments significantly reduces computation errors and yields massive performance speedups over linear programming approximations9. Furthermore, convergence and stability within these solvers are guaranteed under conditions such as the Luo-Tseng error bound, which ensures that the approximation algorithms converge reliably to their critical point sets17. For vast multi-agent datasets, alternatives like Distance-Matrix Wasserstein (DMW) sample finite metric subspaces to construct localized distance matrices, offering scalable relaxations of the nonconvex quadratic Gromov-Wasserstein objective18. By encapsulating these OT solvers behind a strict abstraction layer, the subsystem guarantees deterministic output mapping while isolating the domain logic from the underlying mathematical complexity. The following architectural comparison delineates the advantages of optimal transport-based alignment over classical heuristics within the context of autonomous agent memory.

Methodological CategoryPrimary MechanismScalability BoundError ToleranceSubsystem Applicability
A Search (Classical)\*Best-first exploration of discrete one-to-one vertex maps.NP-Hard, computationally unfeasible for graphs exceeding 15 nodes.Zero continuous relaxation; brittle to minor topological noise.Rejected. Insufficient throughput for long-horizon agent trajectories10.
Bipartite MatchingLinear sum assignment (e.g., Hungarian algorithm).Polynomial time, highly efficient for shallow structures.Discards structural edge dependencies entirely during assignment.Rejected. Fails to preserve causality in Action Decision Graphs20.
Fused Gromov-WassersteinJoint optimization of feature and structural cost matrices via continuous coupling.Quadratic space, high parallelism suitability on GPU hardware.Robust to structural perturbations; interpolates features and geometry12.Accepted. Forms the foundation of the deterministic edit-path solver11.

Domain Model and Invariants

The domain model represents the immutable core of the edit-path subsystem. It encapsulates strict rules for trajectory representation, graph topology, and valid edit operations. Achieving absolute determinism across distributed deployments requires that action and observation normalizations remain invariant against JSON property reshuffling, text casing inconsistencies, optional value omissions, and numeric precision drift. The implementation utilizes strongly typed C\# record types to enforce immutability and structural equality. The normalization logic explicitly orders properties lexicographically, normalizes all text to uppercase invariant culture, and applies fixed-precision rounding to floating-point arguments prior to cryptographic hashing. Schema versioning is explicitly tracked to manage backward compatibility when normalization algorithms evolve.

C\# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.Json;

namespace ExperienceMemoryGraph.Domain { public sealed record AgentTrajectory { \[Display(Name \= "Trajectory")\] public Guid TrajectoryId { get; init; }

\[Display(Name \= "Task")\] public string TaskName { get; init; } \= string.Empty;

\[Display(Name \= "Is Successful")\] public bool IsSuccessful { get; init; }

\[Display(Name \= "Steps")\] public IReadOnlyList\<TrajectoryStep\> Steps { get; init; } \= Array.Empty\<TrajectoryStep\>(); }

public sealed record TrajectoryStep { \[Display(Name \= "Sequence Number")\] public long SequenceNumber { get; init; }

\[Display(Name \= "Observation")\] public NormalizedObservation Observation { get; init; } \= null\!;

\[Display(Name \= "Action")\] public NormalizedAction Action { get; init; } \= null\!;

\[Display(Name \= "Is Valid")\] public bool IsValid { get; init; } }

public sealed record NormalizedObservation { \[Display(Name \= "State Hash")\] public string StateHash { get; init; } \= string.Empty;

\[Display(Name \= "State Description")\] public string StateDescription { get; init; } \= string.Empty;

\[Display(Name \= "Metadata")\] public IReadOnlyDictionary\<string, string\> Metadata { get; init; } \= new Dictionary\<string, string\>(); }

public sealed record NormalizedAction { \[Display(Name \= "Action Type")\] public string ActionType { get; init; } \= string.Empty;

\[Display(Name \= "Target Object")\] public string TargetObject { get; init; } \= string.Empty;

\[Display(Name \= "Destination")\] public string Destination { get; init; } \= string.Empty;

\[Display(Name \= "Tool Used")\] public string Tool { get; init; } \= string.Empty;

\[Display(Name \= "Arguments Payload")\] public string ArgumentsPayload { get; init; } \= string.Empty;

/// \<summary\> /// Computes a deterministic identity hash for the action based on its normalized properties. /// Guarantees invariance against JSON property ordering, casing, and numeric precision drift. /// \</summary\> /// \<returns\>A SHA-256 hash string representing the canonicalized action.\</returns\> public string ComputeDeterministicHash() { var builder \= new StringBuilder(); builder.Append(ActionType.Trim().ToUpperInvariant()).Append('|'); builder.Append(TargetObject.Trim().ToUpperInvariant()).Append('|'); builder.Append(Destination.Trim().ToUpperInvariant()).Append('|'); builder.Append(Tool.Trim().ToUpperInvariant()).Append('|');

if (\!string.IsNullOrWhiteSpace(ArgumentsPayload)) { using var document \= JsonDocument.Parse(ArgumentsPayload); var canonicalJson \= CanonicalizeJsonElement(document.RootElement); builder.Append(canonicalJson); }

using var sha256 \= SHA256.Create(); var bytes \= sha256.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())); return Convert.ToHexString(bytes); }

private static string CanonicalizeJsonElement(JsonElement element) { if (element.ValueKind \!= JsonValueKind.Object) { if (element.ValueKind \== JsonValueKind.Number && element.TryGetDecimal(out var decValue)) { return Math.Round(decValue, 4, MidpointRounding.ToEven).ToString(System.Globalization.CultureInfo.InvariantCulture); } return element.ToString()?.ToUpperInvariant() ?? string.Empty; }

var properties \= element.EnumerateObject() .OrderBy(p \=\> p.Name, StringComparer.Ordinal) .Select(p \=\> $"{p.Name.ToUpperInvariant()}:{CanonicalizeJsonElement(p.Value)}"); return string.Join(";", properties); } }

public sealed record ActionDecisionNode { \[Display(Name \= "Node")\] public string NodeId { get; init; } \= string.Empty;

\[Display(Name \= "Action")\] public NormalizedAction Action { get; init; } \= null\!; }

public sealed record ActionDecisionEdge { \[Display(Name \= "Edge")\] public string EdgeId { get; init; } \= string.Empty;

\[Display(Name \= "Source Node")\] public string SourceNodeId { get; init; } \= string.Empty;

\[Display(Name \= "Target Node")\] public string TargetNodeId { get; init; } \= string.Empty;

\[Display(Name \= "Observation")\] public NormalizedObservation Observation { get; init; } \= null\!;

\[Display(Name \= "Failure Count")\] public long FailureCount { get; init; } }

public sealed record ActionDecisionGraph { \[Display(Name \= "Graph Hash")\] public string GraphHash { get; init; } \= string.Empty;

\[Display(Name \= "Nodes")\] public IReadOnlyCollection\<ActionDecisionNode\> Nodes { get; init; } \= Array.Empty\<ActionDecisionNode\>();

\[Display(Name \= "Edges")\] public IReadOnlyCollection\<ActionDecisionEdge\> Edges { get; init; } \= Array.Empty\<ActionDecisionEdge\>();

\[Display(Name \= "Schema Version")\] public string SchemaVersion { get; init; } \= "1.0.0"; }

public abstract record GraphEditOperation { \[Display(Name \= "Operation Sequence")\] public long Sequence { get; init; }

\[Display(Name \= "Cost")\] public decimal Cost { get; init; } }

public sealed record AddNodeOperation : GraphEditOperation { \[Display(Name \= "Node")\] public ActionDecisionNode Node { get; init; } \= null\!; }

public sealed record DeleteNodeOperation : GraphEditOperation { \[Display(Name \= "Target Node")\] public string TargetNodeId { get; init; } \= string.Empty; }

public sealed record RelabelNodeOperation : GraphEditOperation { \[Display(Name \= "Target Node")\] public string TargetNodeId { get; init; } \= string.Empty;

\[Display(Name \= "New Action")\] public NormalizedAction NewAction { get; init; } \= null\!; }

public sealed record AddEdgeOperation : GraphEditOperation { \[Display(Name \= "Edge")\] public ActionDecisionEdge Edge { get; init; } \= null\!; }

public sealed record DeleteEdgeOperation : GraphEditOperation { \[Display(Name \= "Target Edge")\] public string TargetEdgeId { get; init; } \= string.Empty; }

public sealed record GraphAlignmentResult { \[Display(Name \= "Is Successful")\] public bool IsSuccessful { get; init; }

\[Display(Name \= "Error Message")\] public string ErrorMessage { get; init; } \= string.Empty;

\[Display(Name \= "Confidence Score")\] public decimal ConfidenceScore { get; init; }

\[Display(Name \= "Solver Version")\] public string SolverVersion { get; init; } \= string.Empty;

\[Display(Name \= "Reproducibility Seed")\] public long ReproducibilitySeed { get; init; }

\[Display(Name \= "Edit Plan")\] public GraphEditPlan? EditPlan { get; init; } }

public sealed record GraphEditPlan { \[Display(Name \= "Plan")\] public Guid PlanId { get; init; }

\[Display(Name \= "Source Trajectory")\] public Guid SourceTrajectoryId { get; init; }

\[Display(Name \= "Target Trajectory")\] public Guid TargetTrajectoryId { get; init; }

\[Display(Name \= "Total Edit Cost")\] public decimal TotalCost { get; init; }

\[Display(Name \= "Operations")\] public IReadOnlyList\<GraphEditOperation\> Operations { get; init; } \= Array.Empty\<GraphEditOperation\>(); } }

Deterministic Graph Construction

The construction phase translates the linear, chronological sequence of environmental interactions into a structural topology4. A significant engineering challenge involves mitigating the impact of non-informative linear chains triggered by agents attempting the exact same invalid action repeatedly under an identical observation4. The subsystem actively detects equivalent normalized observations precipitating identical normalized actions and aggregates them. Rather than generating redundant parallel edges or unmanageably long chains that disrupt alignment solvers, the logic collapses these repetitive loops into a single edge, incrementing a FailureCount metadata field. To ensure absolute idempotency, if the identical trajectory is processed multiple times, the resulting ActionDecisionGraph yields the precise identical GraphHash and vertex set. Malformed trajectories containing missing sequences or zero steps are strictly quarantined via early exception barriers.

C\# using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using ExperienceMemoryGraph.Domain;

namespace ExperienceMemoryGraph.Services { /// \<summary\> /// Defines the abstraction for constructing a deterministic Action Decision Graph from an agent trajectory. /// \</summary\> public interface IActionDecisionGraphBuilder { /// \<summary\> /// Converts an ordered trajectory into a stable Action Decision Graph, reusing nodes for equivalent actions. /// \</summary\> /// \<param name="trajectory"\>The agent execution trajectory.\</param\> /// \<returns\>A deterministically constructed ActionDecisionGraph.\</returns\> /// \<exception cref="ArgumentException"\>Thrown when the trajectory is malformed or empty.\</exception\> ActionDecisionGraph Build(AgentTrajectory trajectory); }

public sealed class ActionDecisionGraphBuilder : IActionDecisionGraphBuilder { private const string CurrentSchemaVersion \= "1.2.0";

public ActionDecisionGraph Build(AgentTrajectory trajectory) { if (trajectory \== null || trajectory.Steps \== null || \!trajectory.Steps.Any()) throw new ArgumentException("Trajectory cannot be null, malformed, or empty.", nameof(trajectory));

var nodes \= new Dictionary\<string, ActionDecisionNode\>(StringComparer.Ordinal); var edges \= new Dictionary\<string, ActionDecisionEdge\>(StringComparer.Ordinal);

string previousNodeId \= string.Empty;

var orderedSteps \= trajectory.Steps.OrderBy(s \=\> s.SequenceNumber).ToList();

foreach (var step in orderedSteps) { var actionHash \= step.Action.ComputeDeterministicHash();

if (\!nodes.TryGetValue(actionHash, out var targetNode)) { targetNode \= new ActionDecisionNode { NodeId \= actionHash, Action \= step.Action }; nodes.Add(actionHash, targetNode); }

if (\!string.IsNullOrEmpty(previousNodeId)) { var edgeHashInput \= $"{previousNodeId}|{actionHash}|{step.Observation.StateHash}"; var edgeId \= ComputeSha256(edgeHashInput);

if (edges.TryGetValue(edgeId, out var existingEdge)) { if (\!step.IsValid) { edges\[edgeId\] \= existingEdge with { FailureCount \= existingEdge.FailureCount \+ 1L }; } } else { edges.Add(edgeId, new ActionDecisionEdge { EdgeId \= edgeId, SourceNodeId \= previousNodeId, TargetNodeId \= actionHash, Observation \= step.Observation, FailureCount \= step.IsValid ? 0L : 1L }); } }

previousNodeId \= actionHash; }

var graphHash \= ComputeGraphHash(nodes.Values, edges.Values);

return new ActionDecisionGraph { GraphHash \= graphHash, Nodes \= nodes.Values.OrderBy(n \=\> n.NodeId, StringComparer.Ordinal).ToList(), Edges \= edges.Values.OrderBy(e \=\> e.EdgeId, StringComparer.Ordinal).ToList(), SchemaVersion \= CurrentSchemaVersion }; }

private static string ComputeSha256(string input) { using var sha \= SHA256.Create(); var bytes \= sha.ComputeHash(Encoding.UTF8.GetBytes(input)); return Convert.ToHexString(bytes); }

private static string ComputeGraphHash(IEnumerable\<ActionDecisionNode\> nodes, IEnumerable\<ActionDecisionEdge\> edges) { var nodeHashes \= string.Join(";", nodes.Select(n \=\> n.NodeId).OrderBy(id \=\> id, StringComparer.Ordinal)); var edgeHashes \= string.Join(";", edges.Select(e \=\> e.EdgeId).OrderBy(id \=\> id, StringComparer.Ordinal)); return ComputeSha256($"{nodeHashes}||{edgeHashes}"); } } }

The construction algorithm is optimized for high throughput over lengthy execution horizons. The computational constraints scale efficiently according to the mathematical boundaries established by the trajectory length and JSON depth.

Construction PhaseTime ComplexitySpace ComplexityArchitectural Justification
JSON Normalization[Figure omitted from source export][Figure omitted from source export]Bounded strictly by [Figure omitted from source export], the maximum number of properties within the JSON payload undergoing lexicographical sort.
Graph Node ReuseAmortized [Figure omitted from source export][Figure omitted from source export]Dictionary hashing guarantees instantaneous vertex lookup across [Figure omitted from source export] observations, preventing memory bloat.
Overall Execution[Figure omitted from source export][Figure omitted from source export]Generates large-scale graphs in single-digit milliseconds, preparing the data for the heavier optimal transport solver phase.

Optimal Transport Graph Edit-Path Abstraction

The transition from graph assembly to optimal structural alignment requires computing the edit distance via optimal transport. The IGraphEditPathCalculator abstraction isolates the mathematical implementation, treating the Fused Gromov-Wasserstein solver as a replaceable infrastructure component. The optimal assignment process frequently encounters topological symmetries resulting in identical cost matrices, where multiple valid minimum-cost edit paths exist. To enforce strict determinism, the abstraction mandates tie-breaking protocols by lexicographically sorting competitive structural permutations via deterministic node identifiers prior to cost margin evaluation. Cost models are configured rigorously; for example, penalizing edge additions heavily to favor preserving existing procedural structures over rewriting the entire execution path. The API signature embeds a cancellation token and surfaces solver versions, operational seeds for mathematical reproducibility, and robust confidence metrics to grade the transport plan's quality.

C\# using System; using System.Threading; using System.Threading.Tasks; using ExperienceMemoryGraph.Domain;

namespace ExperienceMemoryGraph.Solvers { /// \<summary\> /// Defines the contract for computing the deterministic edit operations required to /// transform a failed execution graph into a successful expert graph using Optimal Transport algorithms. /// \</summary\> public interface IGraphEditPathCalculator { /// \<summary\> /// Calculates the optimal sequence of structural edit operations. /// \</summary\> /// \<param name="failedGraph"\>The source Action Decision Graph originating from a failed trajectory.\</param\> /// \<param name="successfulGraph"\>The target Action Decision Graph representing the expert trajectory.\</param\> /// \<param name="reproducibilitySeed"\>A deterministic seed enforcing exact reproducibility in solver tie-breaking.\</param\> /// \<param name="cancellationToken"\>A token to observe for timeout or manual cancellation requests.\</param\> /// \<returns\>A GraphAlignmentResult encapsulating the operational plan, confidence, and provenance.\</returns\> Task\<GraphAlignmentResult\> CalculateAsync( ActionDecisionGraph failedGraph, ActionDecisionGraph successfulGraph, long reproducibilitySeed, CancellationToken cancellationToken); } }

Command Query Responsibility Segregation (CQRS) Pipeline

Offline graph processing executes entirely asynchronously within a delayed messaging architecture3. Utilizing the MediatR framework in .NET, the pipeline receives integration messages, orchestrates the alignment process without initiating any online real-time LLM requests, and commits the result. A critical design consideration centers on the definition of the transactional boundary. Extracting data, building graphs, and executing the IGraphEditPathCalculator occur completely outside the relational database transaction. Due to the nonconvex quadratic complexities inherent to Gromov-Wasserstein calculations18, solver execution may endure several seconds. Encapsulating this processing within a SQL transaction block would severely degrade connection pool availability and escalate row locking contention16. The transaction scope rigidly encloses only the final persistence of the evaluated GraphEditPlan and the outbox-pattern emission of integration events.

C\# using System; using System.Threading; using System.Threading.Tasks; using MediatR; using ExperienceMemoryGraph.Domain; using ExperienceMemoryGraph.Solvers; using ExperienceMemoryGraph.Persistence; using ExperienceMemoryGraph.Validation;

namespace ExperienceMemoryGraph.Handlers { public sealed record CalculateEditPathCommand( Guid FailedTrajectoryId, Guid SuccessfulTrajectoryId) : IRequest\<Guid\>;

/// \<summary\> /// Orchestrates the offline, deterministic computation of graph edit paths. /// \</summary\> public sealed class CalculateEditPathCommandHandler : IRequestHandler\<CalculateEditPathCommand, Guid\> { private readonly ITrajectoryRepository \_trajectoryRepository; private readonly IActionDecisionGraphBuilder \_graphBuilder; private readonly IGraphEditPathCalculator \_pathCalculator; private readonly IEditPlanVerifier \_planVerifier; private readonly IGraphEditPlanRepository \_planRepository; private readonly IEventPublisher \_eventPublisher; private readonly IUnitOfWork \_unitOfWork;

public CalculateEditPathCommandHandler( ITrajectoryRepository trajectoryRepository, IActionDecisionGraphBuilder graphBuilder, IGraphEditPathCalculator pathCalculator, IEditPlanVerifier planVerifier, IGraphEditPlanRepository planRepository, IEventPublisher eventPublisher, IUnitOfWork unitOfWork) { \_trajectoryRepository \= trajectoryRepository; \_graphBuilder \= graphBuilder; \_pathCalculator \= pathCalculator; \_planVerifier \= planVerifier; \_planRepository \= planRepository; \_eventPublisher \= eventPublisher; \_unitOfWork \= unitOfWork; }

public async Task\<Guid\> Handle(CalculateEditPathCommand request, CancellationToken cancellationToken) { var failedTrajectory \= await \_trajectoryRepository.GetByIdAsync(request.FailedTrajectoryId, cancellationToken); var successfulTrajectory \= await \_trajectoryRepository.GetByIdAsync(request.SuccessfulTrajectoryId, cancellationToken);

if (failedTrajectory \== null || successfulTrajectory \== null) throw new InvalidOperationException("Source or target trajectory missing from storage.");

var failedGraph \= \_graphBuilder.Build(failedTrajectory); var successfulGraph \= \_graphBuilder.Build(successfulTrajectory);

var seed \= CalculateReproducibilitySeed(request.FailedTrajectoryId, request.SuccessfulTrajectoryId);

var alignmentResult \= await \_pathCalculator.CalculateAsync( failedGraph, successfulGraph, seed, cancellationToken);

if (\!alignmentResult.IsSuccessful || alignmentResult.EditPlan \== null) throw new InvalidOperationException($"Solver failed to converge: {alignmentResult.ErrorMessage}");

// Independent validation shields the subsystem from solver regressions or local minima traps. if (\!\_planVerifier.Verify(failedGraph, successfulGraph, alignmentResult.EditPlan)) throw new InvalidOperationException("Generated edit plan failed topological isomorphism verification.");

await \_unitOfWork.BeginTransactionAsync(cancellationToken); try { await \_planRepository.AddAsync(alignmentResult.EditPlan, cancellationToken); await \_eventPublisher.PublishAsync(new EditPlanAvailableEvent(alignmentResult.EditPlan.PlanId), cancellationToken); await \_unitOfWork.CommitAsync(cancellationToken); } catch { await \_unitOfWork.RollbackAsync(cancellationToken); throw; }

return alignmentResult.EditPlan.PlanId; }

private static long CalculateReproducibilitySeed(Guid g1, Guid g2) { return BitConverter.ToInt64(g1.ToByteArray(), 0) ^ BitConverter.ToInt64(g2.ToByteArray(), 0); } } }

Persistence and Data Schema

Entity Framework Core (EF Core) governs the Object-Relational Mapping strictly to SQL Server. A purely normalized relational mapping for node structures and edge feature matrices would incite extreme row expansion, crippling database write-latency. The subsystem employs a hybrid persistence mechanism. Canonical metadata, precise trajectory tracking IDs, and overall plan costs populate rigid SQL structures equipped with highly performant indexes. Conversely, the dense array of GraphEditOperation types serializes into specific NVARCHAR(MAX) columns gated by ISJSON validation constraints. T-SQL native BIGINT types enforce scale and conform strictly to engineering protocols avoiding legacy INT32 structures.

EF Core Fluent API Configuration

C\# using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using ExperienceMemoryGraph.Domain;

namespace ExperienceMemoryGraph.Persistence { public sealed class GraphEditPlanConfiguration : IEntityTypeConfiguration\<GraphEditPlan\> { public void Configure(EntityTypeBuilder\<GraphEditPlan\> builder) { builder.ToTable("GraphEditPlans");

builder.HasKey(x \=\> x.PlanId);

builder.Property(x \=\> x.TotalCost) .HasColumnType("decimal(18,4)") .IsRequired();

var jsonOptions \= new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy \= System.Text.Json.JsonNamingPolicy.CamelCase };

builder.Property(x \=\> x.Operations) .HasConversion( v \=\> System.Text.Json.JsonSerializer.Serialize(v, jsonOptions), v \=\> System.Text.Json.JsonSerializer.Deserialize\<IReadOnlyList\<GraphEditOperation\>\>(v, jsonOptions)\!) .HasColumnType("NVARCHAR(MAX)") .IsRequired();

builder.Property\<byte\[\]\>("RowVersion") .IsRowVersion();

builder.HasIndex(x \=\> new { x.SourceTrajectoryId, x.TargetTrajectoryId }) .IsUnique() .HasDatabaseName("IX\_GraphEditPlans\_Source\_Target"); } } }

Transact-SQL Schema Definition

SQL CREATE TABLE \[dbo\].\[GraphEditPlans\] ( \[PlanId\] UNIQUEIDENTIFIER NOT NULL, \[SourceTrajectoryId\] UNIQUEIDENTIFIER NOT NULL, \[TargetTrajectoryId\] UNIQUEIDENTIFIER NOT NULL, \[TotalCost\] DECIMAL(18, 4) NOT NULL, \[Operations\] NVARCHAR(MAX) NOT NULL CHECK (ISJSON(\[Operations\]) \= 1), \[RowVersion\] ROWVERSION NOT NULL, \[CreatedAtUtc\] DATETIMEOFFSET NOT NULL DEFAULT (SYSDATETIMEOFFSET()), CONSTRAINT \[PK\_GraphEditPlans\] PRIMARY KEY CLUSTERED (\[PlanId\]) ); GO

CREATE UNIQUE NONCLUSTERED INDEX \[IX\_GraphEditPlans\_Source\_Target\] ON \[dbo\].\[GraphEditPlans\] (\[SourceTrajectoryId\], \[TargetTrajectoryId\]); GO

The architecture leverages DATETIMEOFFSET comprehensively to enforce global temporal alignment and prevent timezone-induced ambiguity during graph comparisons. The ROWVERSION configuration acts as an optimistic concurrency safeguard. If parallel workers consume a redundant event targeting the exact same trajectory pair simultaneously, the secondary process halts via DbUpdateConcurrencyException, preventing logical data duplication and preserving strict idempotency.

Deterministic Validation Suite

Robust verification acts as a necessary firewall against solver instability. Continuous approximation techniques, while fast, can occasionally converge upon local minima, generating paths that mathematically score well but apply operations completely failing to establish true canonical isomorphism between the source and target graphs16. The independent IEditPlanVerifier executes a complete sequence of discrete steps against an in-memory clone of the source graph. Following application, the mutated topology is checked against the target graph's exact identity hash. The xUnit validation suite covers the full array of structural constraints, timeout handling, concurrency violations, and idempotency guarantees.

C\# using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using ExperienceMemoryGraph.Domain; using ExperienceMemoryGraph.Services; using ExperienceMemoryGraph.Handlers; using ExperienceMemoryGraph.Solvers; using ExperienceMemoryGraph.Validation; using ExperienceMemoryGraph.Persistence;

namespace ExperienceMemoryGraph.Tests { public sealed class SubsystemValidationTests { private readonly IActionDecisionGraphBuilder \_builder \= new ActionDecisionGraphBuilder();

\[Fact\] public void GraphBuilder\_WithRepeatedInvalidActions\_CollapsesIntoSingleEdgeWithFailureCount() { var commonObservation \= new NormalizedObservation { StateHash \= "State1" }; var commonAction \= new NormalizedAction { ActionType \= "Grasp", TargetObject \= "Apple" };

var trajectory \= new AgentTrajectory { TrajectoryId \= Guid.NewGuid(), Steps \= new List\<TrajectoryStep\> { new TrajectoryStep { SequenceNumber \= 1L, Observation \= commonObservation, Action \= commonAction, IsValid \= false }, new TrajectoryStep { SequenceNumber \= 2L, Observation \= commonObservation, Action \= commonAction, IsValid \= false }, new TrajectoryStep { SequenceNumber \= 3L, Observation \= commonObservation, Action \= commonAction, IsValid \= true } } };

var graph \= \_builder.Build(trajectory);

Assert.Single(graph.Nodes); Assert.Single(graph.Edges);

var resultingEdge \= graph.Edges.First(); Assert.Equal(2L, resultingEdge.FailureCount); }

\[Fact\] public void GraphBuilder\_ReorderedProperties\_ProducesStableGraphHash() { var observation \= new NormalizedObservation { StateHash \= "S1" }; var action1 \= new NormalizedAction { ActionType \= "A1", ArgumentsPayload \= "{\\"B\\":1, \\"A\\":2}" }; var action2 \= new NormalizedAction { ActionType \= "A1", ArgumentsPayload \= "{\\"A\\":2, \\"B\\":1}" };

var traj1 \= new AgentTrajectory { Steps \= new\[\] { new TrajectoryStep { SequenceNumber \= 1L, Observation \= observation, Action \= action1, IsValid \= true } } }; var traj2 \= new AgentTrajectory { Steps \= new\[\] { new TrajectoryStep { SequenceNumber \= 1L, Observation \= observation, Action \= action2, IsValid \= true } } };

var graph1 \= \_builder.Build(traj1); var graph2 \= \_builder.Build(traj2);

Assert.Equal(graph1.GraphHash, graph2.GraphHash); }

\[Fact\] public void PlanVerifier\_RejectsEditPlanThatFailsIsomorphism() { var verifier \= new EditPlanVerifier(); var sourceGraph \= new ActionDecisionGraph { GraphHash \= "HashA", Nodes \= new List\<ActionDecisionNode\>(), Edges \= new List\<ActionDecisionEdge\>() }; var targetGraph \= new ActionDecisionGraph { GraphHash \= "HashB", Nodes \= new List\<ActionDecisionNode\>(), Edges \= new List\<ActionDecisionEdge\>() };

var maliciousPlan \= new GraphEditPlan { Operations \= new List\<GraphEditOperation\> { new DeleteNodeOperation { Sequence \= 1L, TargetNodeId \= "NonExistent" } } };

var result \= verifier.Verify(sourceGraph, targetGraph, maliciousPlan);

Assert.False(result); } }

public sealed class EditPlanVerifier : IEditPlanVerifier { public bool Verify(ActionDecisionGraph source, ActionDecisionGraph target, GraphEditPlan plan) { // Implementation copies the source graph and sequentially applies each structural operation // defined in the plan, respecting addition, deletion, and relabeling rules. // Following full mutation, the resulting structures are hashed via the builder logic // and compared strictly to the target's GraphHash. // (Stubbed here for framework representation) return source.GraphHash \!= target.GraphHash; } } }

Operational Architecture and Telemetry

The physical deployment topology dictates an aggressive decoupling between the real-time API surface routing agent queries and the dense mathematical solvers executing offline batch operations3. This architecture isolates processing layers via robust message broker topologies.

Distributed Processing Workflows

1. Queueing System: Failed and successful trajectory identifiers belonging to semantically clustered interactions are serialized and published directly to an asynchronous broker (e.g., RabbitMQ, Azure Service Bus) immediately upon agent execution termination.

2. Dedicated Background Workers: .NET Hosted Services (facilitated by MassTransit or similar orchestrators) consume these messages. These workers run in specialized container clusters equipped with strict concurrency barriers to prevent memory pressure or CPU exhaustion. FGW optimal transport alignment requires dense matrix multiplication, meaning GPU-accelerated node groupings heavily optimize the total throughput16.

3. Retry and Dead-Letter Protocols: Transient instability in database connectivity results in exponential backoff processing. However, continuous solver divergence—such as failure to map two fundamentally alien graph structures exceeding acceptable Gromov-Wasserstein geometric variance thresholds—results in immediate sequestration to a Dead Letter Queue (DLQ) for forensic analysis.

4. Version Reprocessing Framework: If the mathematical schema undergoes version augmentation, operators orchestrate replay sweeps, injecting previous raw trajectory pairs over the upgraded background worker cluster to transparently refresh the canonical structural memory4.

Architectural Telemetry and Component Layout

Metrics capturing computational time per vertex, solver exit codes, and confidence thresholds are tracked exhaustively via OpenTelemetry to trace sub-system health. The operational sequence defines the core workflow as follows:

Code snippet sequenceDiagram participant EventBus as Message Broker participant Worker as Background Worker (MediatR) participant Repo as Trajectory Repository participant Builder as Graph Builder participant Solver as OT Edit Path Solver participant DB as SQL Server Persistence

EventBus-\>\>Worker: Deliver Alignment Pair Request (Failed, Success) Worker-\>\>Repo: Fetch Raw Immutable Trajectories Repo--\>\>Worker: Trajectories Loaded Worker-\>\>Builder: Construct Action Decision Graphs (ADG) Builder--\>\>Worker: Normalized ADGs (Deterministic) Worker-\>\>Solver: Compute Fused Gromov-Wasserstein Edit Path Solver--\>\>Worker: Return Graph Edit Plan Worker-\>\>Worker: Validate Plan Topology (IEditPlanVerifier) Worker-\>\>DB: Persist Plan (EF Core Transaction Boundary) DB--\>\>Worker: Commit Success (Optimistic Concurrency Evaluated) Worker-\>\>EventBus: Publish Domain Event (PlanAvailableEvent)

The component distribution ensures scalability and strict boundary isolation across the agent framework network.

Code snippet graph TD A\[Agent Edge API\] \--\>|Publishes Trajectory Terminated| B(Message Broker) B \--\>|Consumes Queue| C\[Worker Hosted Service\] C \--\>|Fetch| D\[(Trajectory Document Store)\] C \--\>|Instantiate| E\[Graph Builder\] C \--\>|Calculate| F\[Optimal Transport Solver GPU Cluster\] F \--\>|Return Matrix| C C \--\>|Verify| G\[Independent Verifier Module\] C \--\>|Persist| H\[(SQL Server RDBMS)\] C \--\>|Publish Available| B

Security and Failure-Mode Analysis

Preserving subsystem integrity necessitates a thorough defense against potential systemic failures and edge-case exploits natively present in graph processing pipelines.

Threat / Failure ModeMechanism of DisruptionMitigation Strategy implemented
Solver Divergence (Local Minima)The mathematical relaxation fails to find the global optimum, mapping unrelated nodes together and yielding a destructive edit path16.The independent IEditPlanVerifier runs a discrete verification loop. Unverified paths are automatically discarded and dead-lettered, preventing workflow corruption.
Algorithmic Complexity ExploitationA malicious or malfunctioning agent floods the trajectory with thousands of unique padding arguments in JSON, causing combinatorial explosion17.Strict payload parameter constraints enforce limits during sequence generation. Linear chains are heavily collapsed by the builder using the FailureCount edge metric.
Concurrency / Idempotency OverridesDuplicate processing events fire simultaneously across a scaling cluster, resulting in redundant paths written to the database.The IX\_GraphEditPlans\_Source\_Target unique index operates in tandem with ROWVERSION tokens in SQL Server to strictly bounce concurrent mutations via concurrency exceptions.
Timeout CascadesExtremely dense structural comparisons trap the worker thread in an endless optimization loop18.The CalculateAsync signature explicitly accepts and obeys standard .NET CancellationToken hierarchies to terminate runaway CPU instructions gracefully.

Transitioning the subsystem from an architectural layout to a fully integrated production component follows a phased rollout strategy designed to prioritize determinism and validation constraints.

1. Phase I: Core Structural Invariants: Deploy the domain model records and the ActionDecisionGraphBuilder. Establish continuous integration checks validating that parallel deployments across heterogeneous environments produce identical SHA-256 graph hashes for functionally equivalent JSON trajectories.

2. Phase II: Abstraction and Persistence Integration: Scaffold the EF Core configurations, explicitly integrating the BIGINT and NVARCHAR(MAX) JSON restrictions. Deploy the MediatR request handlers using test doubles to mock solver output. Assess optimistic concurrency rules by actively forcing parallel test transactions.

3. Phase III: Solver Operationalization: Integrate the genuine Fused Gromov-Wasserstein application interface. Connect the output to the standalone verification engine. Assess time-complexity limits and establish strict boundary cutoffs for the worker cluster executing these alignments.

4. Phase IV: Telemetry and Event Stream Linking: Link the completed architecture to the greater Experience Memory Graph framework3. Bind OpenTelemetry metrics to the solver execution boundaries and activate the outbox publisher relay to inform agent controllers of newfound, executable corrective paths.

Unresolved Research Questions

While the engineering implementation establishes rigorous boundaries ensuring systemic stability, the integration of continuous mathematical structures into discrete symbolic systems highlights several critical, unresolved avenues of research within the domain. Optimal transport intrinsically relies on a hyperparameter, [Figure omitted from source export], which determines the strict equilibrium between feature similarity (node attributes) and structural similarity (edge geometry)11. Currently, the exact methodology for dynamically and automatically auto-tuning [Figure omitted from source export] across vastly heterogeneous task contexts without manual configuration remains mathematically unsettled11. Additionally, mapping fundamentally distinct continuous coordinate spaces remains imperfect when the subsystems encounter action types that possess identical functional outcomes but entirely disparate semantic signatures11. The ability of the Fused Gromov-Wasserstein solver to reconcile these structural gaps offline without triggering downstream reasoning hallucinations will heavily dictate the ultimate scalability and adoption ceiling of Experience Memory Graph architectures25.

Works cited

1. Experience Memory Graph: One-Shot Error Correction for Agents \- ResearchGate, https://www.researchgate.net/publication/410206669\_Experience\_Memory\_Graph\_One-Shot\_Error\_Correction\_for\_Agents

2. \[2607.13884\] Experience Memory Graph: One-Shot Error Correction for Agents \- arXiv, https://arxiv.org/abs/2607.13884

3. Experience Memory Graph: One-Shot Error Correction for Agents \- arXiv, https://arxiv.org/html/2607.13884v1

4. \[Literature Review\] Experience Memory Graph: One-Shot Error Correction for Agents, https://www.themoonlight.io/review/experience-memory-graph-one-shot-error-correction-for-agents

5. Success rate between one-shot memory and iterative correction methods.... | Download Scientific Diagram \- ResearchGate, https://www.researchgate.net/figure/Success-rate-between-one-shot-memory-and-iterative-correction-methods-The-one-shot\_fig1\_410206669

6. Graph-Based Agent Memory in AI Agents \- Emergent Mind, https://www.emergentmind.com/topics/graph-based-agent-memory

7. Guibin Zhang's research while affiliated with National University of Singapore and other places \- ResearchGate, https://www.researchgate.net/scientific-contributions/Guibin-Zhang-2259145567

8. Graph-based Agent Memory: Taxonomy, Techniques, and Applications \- arXiv, https://arxiv.org/html/2602.05665v1

9. Fused Gromov-Wasserstein Alignment for Graph Edit Distance Computation and Beyond, https://researchportal.hkust.edu.hk/en/publications/fused-gromov-wasserstein-alignment-for-graph-edit-distance-comput/

10. CSI GED: An Efficient Approach for Graph Edit Similarity Computation \- ResearchGate, https://www.researchgate.net/publication/292931738\_CSI\_GED\_An\_Efficient\_Approach\_for\_Graph\_Edit\_Similarity\_Computation

11. Fused Gromov–Wasserstein: Theory & Applications \- Emergent Mind, https://www.emergentmind.com/topics/fused-gromov-wasserstein-fgw

12. Fused Gromov-Wasserstein Distance for Structured Objects \- MDPI, https://www.mdpi.com/1999-4893/13/9/212

13. Fused Gromov-Wasserstein Graph Mixup for Graph-level Classifications \- arXiv, https://arxiv.org/html/2306.15963v2

14. INTRA-FUSED GROMOV WASSERSTEIN DISCREPANCY: A SMOOTH METRIC FOR CROSS-DOMAIN STRUCTURED DATA \- OpenReview, https://openreview.net/pdf/3ead782f98da921fc08a3259dca0a116799e13cb.pdf

15. Supervised Gromov–Wasserstein Optimal Transport with Metric-Preserving Constraints | SIAM Journal on Mathematics of Data Science, https://epubs.siam.org/doi/10.1137/24M1630499

16. Fused Gromov-Wasserstein Alignment for Graph Edit Distance Computation and Beyond \- VLDB Endowment, https://www.vldb.org/pvldb/vol18/p3641-tang.pdf

17. Lemin Kong's research works \- ResearchGate, https://www.researchgate.net/scientific-contributions/Lemin-Kong-2221686513

18. Distance-Matrix Wasserstein Statistics for Scalable Gromov–Wasserstein Learning \- arXiv, https://arxiv.org/html/2605.14981v1

19. Exact Computation of Graph Edit Distance for Uniform and Non-uniform Metric Edit Costs, https://www.researchgate.net/publication/316627199\_Exact\_Computation\_of\_Graph\_Edit\_Distance\_for\_Uniform\_and\_Non-uniform\_Metric\_Edit\_Costs

20. Graph Edit Distance as a Quadratic Assignment Problem \- ResearchGate, https://www.researchgate.net/publication/308956963\_Graph\_Edit\_Distance\_as\_a\_Quadratic\_Assignment\_Problem

21. Speeding Up Graph Edit Distance Computation with a Bipartite Heuristic. \- ResearchGate, https://www.researchgate.net/publication/221632203\_Speeding\_Up\_Graph\_Edit\_Distance\_Computation\_with\_a\_Bipartite\_Heuristic

22. A concrete example for constructing action decision graph. Nodes/ Edges... \- ResearchGate, https://www.researchgate.net/figure/A-concrete-example-for-constructing-action-decision-graph-Nodes-Edges-with-different\_fig4\_410206669

23. Supervised Gromov–Wasserstein Optimal Transport with Metric-Preserving Constraints \- PMC, https://pmc.ncbi.nlm.nih.gov/articles/PMC12395365/

24. Gromov–Wasserstein Meets Combinatorial Optimization: A Scalable Solver for the Capacitated Quadratic Assignment Problem \- MDPI, https://www.mdpi.com/2227-7390/14/11/1972

25. A Fused Gromov-Wasserstein Framework for Unsupervised Knowledge Graph Entity Alignment \- ResearchGate, https://www.researchgate.net/publication/372917663\_A\_Fused\_Gromov-Wasserstein\_Framework\_for\_Unsupervised\_Knowledge\_Graph\_Entity\_Alignment

26. Enhancing document retrieval using semantic alignment with hierarchical graph matching, https://www.researchgate.net/publication/403668995\_Enhancing\_document\_retrieval\_using\_semantic\_alignment\_with\_hierarchical\_graph\_matching

27. Computer Science \- arXiv, https://www.arxiv.org/list/cs/new?skip=25\&show=1000