Memory and Learning Integrated Control Design
- Author: Masahiro Aoki
- Copyright: 2026 Moonlight Technologies Inc. All Rights Reserved.
- Last updated: 2026-08-15
Overview
The main gap identified in the Sparse Evo-MemoryLM review is not missing subsystems, but the lack of a single production control flow connecting memory, inference, learning, and auditability. This document defines the integrated control layer that closes that gap.
This design is intentionally written as an extension-ready contract rather than a one-off minimal implementation. The current
MemoryOrchestratoris the foundational layer; future integration withMeta-STDP,AEG,ForgettingController,LongTermMemoryModule, and multimodal LM variants should be added by following this specification.
The design connects the following existing assets under one request-scoped execution model.
evospikenet/episodic_memory.pymemory storage, retrieval, and forgettingevospikenet/memory_orchestrator.pyminimal orchestration implementationevospikenet/common.pyAuditLoggerandDataConverter- Learning and stabilization modules such as
Meta-STDP,AEG,ForgettingController, andLongTermMemoryModule
Design goals
- Execute input handling, inference, learning updates, memory write-back, and audit emission in one control flow.
- Make every mandatory stage traceable through a shared
request_id,session_id, andtimestamp. - Prohibit mock and fallback responses on the production path; fail fast on mandatory-stage errors.
- Normalize inference events and learning events into one memory-event contract.
- Define acceptance criteria that include Docker-based SDK/API validation and regression coverage.
Scope
In scope
- Request normalization
- Episodic and semantic memory retrieval
- Pre-execution context fusion
- Lightweight online learning control coupled to inference
- Output, reward, and quality write-back into memory
- Audit logs, operational metrics, and failure contracts
Out of scope
- Replacing the underlying learning algorithms
- Designing new modalities
- Replacing the distributed substrate itself
Architecture
Core components
InputNormalizer- Converts raw input into a standard request envelope.
-
Attaches
source,session_id,actor,tenant, andtrace_tags. -
MemoryRetrievalCoordinator - Extracts semantic tags, selects retrieval strategy, and controls top-k.
-
Collects episodic and semantic results in parallel and deduplicates them.
-
ContextFusionEngine - Merges retrieved memories, session state, and learning state into
MemoryContextPayload. -
Trims noise and enforces model-context size limits.
-
LearningControlCoordinator - Governs
Meta-STDP,AEG,ForgettingController, and long-term memory updates. -
Decides whether updates are allowed from reward, loss proxy, and quality signals.
-
ExecutionPolicy - Chooses between inference-only, inference-plus-learning, and learning-disabled modes.
-
Evaluates safety, capacity, and convergence protection rules.
-
AuditTrailEmitter - Emits structured logs through
AuditLogger.log_event()andDataConverter.convert_to_structured_event(). - Records successful inference, learning updates, and write-back failures in one event stream.
Standard data contracts
Required headers
Every event and internal payload must carry the following fields.
request_idsession_idsourcetimestamppipeline_stage
Execution context
Use the existing MemoryContextPayload as the base type and elevate the following fields to operationally required status.
user_inputsemantic_contextepisodic_contextretrieved_memoriesgenerated_outputmetadata.learning_modemetadata.reward_signalmetadata.quality_score
Memory events
Use MemoryEventRecord as the operation log with the following canonical event types.
retrieval_startedretrieval_completedmodel_execution_startedmodel_execution_completedlearning_update_startedlearning_update_completedmemory_writeback_startedmemory_writeback_completedpipeline_failed
Learning control signal
The implementation should introduce the following dataclass.
@dataclass
class LearningControlSignal:
request_id: str
session_id: str
reward: float
quality_score: float
loss_proxy: float | None
gradient_norm: float | None
safe_to_update: bool
update_reason: str
Execution sequence
flowchart TD
A[Client Request] --> B[InputNormalizer]
B --> C[MemoryRetrievalCoordinator]
C --> D[Episodic Retrieval]
C --> E[Semantic Retrieval]
D --> F[ContextFusionEngine]
E --> F
F --> G[ExecutionPolicy]
G --> H[Model Execution]
H --> I[Quality / Reward Evaluation]
I --> J[LearningControlCoordinator]
J --> K[Memory Writeback]
K --> L[AuditTrailEmitter]
Control modes
Mode A: inference only
- Memory retrieval is mandatory.
- No learning update is performed.
- Only output and evaluation data are recorded.
Mode B: inference plus lightweight online update
- Retrieval and inference are both mandatory.
- Update
Meta-STDPandAEGonly when quality thresholds pass. - Use reward signals only after smoothing.
Mode C: batch consolidation and stabilization
- Runs asynchronously from online requests.
- Executes forgetting, compression, and long-term consolidation.
- Links request-scoped events to scheduled job traces.
Fail-fast contract
This design forbids mock and fallback behavior on the production path. The fallback response still present in the minimal orchestrator implementation is a migration target, not a completion target.
Stop conditions
- Input normalization failure
- Mandatory memory retrieval failure
- Model execution failure
- Learning-control safety violation that cannot be absorbed by update suppression
- Memory write-back failure
Allowed continuation
- Secondary audit-emission failures may be attached as auxiliary diagnostics to the primary exception.
- Non-critical metric-export failures must not mutate the main transaction.
Implementation plan
Phase 1: contract unification
- Refine
MemoryContextPayloadandMemoryEventRecordfor fail-fast operation. - Repurpose
FailureHandlingResultfrom fallback metadata into structured stop-reason metadata. - Route orchestration logs consistently through
common.py.
Phase 2: orchestrator migration
- Remove fallback branches from
MemoryOrchestrator.process_request(). - Emit start and completion events for retrieval, execution, learning, and write-back.
- Add a request-scoped transaction context.
Phase 3: learning-control integration
- Centralize
Meta-STDPandAEGupdate gating inLearningControlCoordinator. - Record
gradient norm,reward clip, andEMA alphaper request. - Make forgetting and long-term consolidation conditions explicit.
Phase 4: validation and production hardening
- Validate the full retrieval-to-writeback path with live SDK/API Docker tests.
- Convert no-degradation behavior into regression tests.
- Verify that audit events can be reconstructed uniquely by
request_id.
Acceptance criteria
user_input -> retrieval -> context fusion -> model execution -> learning update -> memory writebackruns as one control flow.- Mandatory-stage errors terminate explicitly instead of degrading into mock or fallback responses.
- A full request timeline can be reconstructed from
AuditLoggeroutput. Meta-STDP,AEG, and forgetting decisions are persisted as events.- The same contract is verified by both automated tests and Docker-backed SDK validation.
Related documents
- Implementation Status
- Episodic Memory Implementation
- Sparse Event-Memory LM Detailed Mathematics and Memory Design
API contract (updated 2026-08-14)
/api/memory/orchestrate is the unified API entrypoint for memory retrieval, generation, learning update, and write-back within one request-scoped pipeline.
Key request fields
user_input(required)session_id(required)source(optional, defaultapi)request_id(optional)fail_fast(optional, defaulttrue)runtime_model(optional):stub/api_loaded/evolm_backendlm_architecture(optional): LM architecture forruntime_model=evolm_backendmodel_device(optional): device override forruntime_model=evolm_backendallow_stub_fallback(optional, defaulttrue)max_new_tokens(optional, default64)temperature(optional, default1.0)
Key response fields
status:completedordegradedrequest_idruntime_model: requested backend typeeffective_runtime_model: actually used backend typegenerated_outputmetadatamemory_events[]: stage-level event streamfailure: structured failure payload when fail-fast is disabled
Error contract
- When fail-fast is enabled, orchestration failures raise
OrchestrationRuntimeErrorand are converted by API exception mapping into the standard error envelope. - Stage error codes:
MLI-REQ-001MLI-RET-001MLI-EXE-001MLI-LRN-001MLI-WRB-001
Audit-stream consistency requirements
memory_events[].request_idmust match responserequest_id.memory_events[].session_idmust match inputsession_id.- Event order must preserve start-to-end progression from
retrieval_startedthroughmemory_writeback_completed.
Implementation reflection (2026-08-15)
This design is now reflected in the repository as follows:
evospikenet/memory_orchestrator.pygenerates a request-scopedtransaction_idand emitstransaction_started/transaction_committed/transaction_rolled_backaudit events.evospikenet/memory_orchestrator.pynormalizes retrieval results for learning and propagatesrecords,max_capacity,ltm_context, andspike_sequenceintoLearningControlCoordinator.evospikenet/learning_control_coordinator.pywiresMeta-STDP,AEG,ForgettingController, andLongTermMemoryModulethrough a shared request context.evospikenet/memory_writeback_service.pypreservestransaction_idin the write-back context.evospikenet/execution_policy.pywas corrected after integrated-path validation exposed a missingloggingimport that caused 500/NameError failures.- Tests and CI now include
tests/unit/test_priority1_learning_control_unit.py,tests/integration/test_priority1_memory_orchestrator_integration.py,tests/e2e/test_priority1_memory_orchestrate_api_e2e.py,tests/performance/test_priority1_memory_orchestrator_performance.py,.github/workflows/priority1-memory-orchestrator.yml, and theMakefiletargetpriority1-memory-orchestrator-test. - Validation:
make priority1-memory-orchestrator-testpassed underProduct/venvwith 5 tests.