You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[geaflow/ai-memory] Define VectorStore SPI with model metadata #851
Context: EmbeddingIndexStore stores embeddings for GraphEntity in JSONL and memory map. Phase 1 needs a generic vector store contract for both chunks and graph entities.
Hi ,
I have gone ahead and implemented this.
I created the VectorStore SPI interface and the VectorStoreMetadata class and added the required test cases as requested.
Hello @Sumit2342, I'm glad to see your contribution. However, this VectorStore SPI layer is an intermediate layer in the graph memory, bridging the gap between higher and lower layers. Therefore, we hope it can support different types of search abstractions. Below are some suggestions for your reference.
1. Background and Motivation
1.1 Problem Statement
The current EmbeddingIndexStore couples storage, index building, and similarity computation into a single monolithic class. Every layer in the pipeline is non-replaceable:
// Current architecture — tightly coupledpublicclassEmbeddingIndexStoreimplementsIndexStore {
// Storage: in-memory HashMap + append-only JSONLprivatefinalHashMap<GraphEntity, List<EmbeddingResult>> embeddingMap = newHashMap<>();
// Index building: scans all vertices/edges, calls EmbeddingServicepublicvoidbuildIndex(MemoryGraphgraph) { ... }
// Retrieval: returns EmbeddingVector wrapping stored double[]publicList<IVector> getEntityIndex(GraphEntityentity) { ... }
// Similarity: EmbeddingVector.match() does brute-force linear scan externally
}
This means:
No pluggable storage backend: the HashMap and JSONL file are hardcoded; switching to a different persistence mechanism requires rewriting the entire class.
No chunk vector support: the store only accepts GraphEntity as keys. Phase 1 requires indexing document chunks (GM-AI-P1-018), which have a fundamentally different key type (chunk_id vs GraphEntity).
No metadata contract: there is no formal definition of what metadata accompanies a stored vector (model name, dimension, distance metric, format version). Without this, cross-store queries cannot validate compatibility.
No test surface: EmbeddingIndexStore has zero unit tests. The coupling makes it impossible to test storage behavior in isolation.
// Example of the coupling problem:// To test "does this store reject wrong-dimension vectors?",// you must construct a full MemoryGraph, build all indexes,// and run a complete search pipeline. There is no isolated test point.
Core contradiction: Phase 1 requires two independent vector consumers — ChunkVectorIndex (GM-AI-P1-018) and EntityVectorIndex (GM-AI-P1-019) — that share the same storage protocol but serve different source types. Without a unified VectorStore SPI, these two issues will each invent their own storage, producing incompatible implementations.
1.2 Quantified Impact
Scenario
Issue without VectorStore SPI
Consequence
ChunkVectorIndex (018) and EntityVectorIndex (019) built independently
Each defines its own storage format, metadata, and query semantics
Two incompatible vector stores; hybrid retrieval (GM-AI-P1-036) cannot fuse results
ANN adapter (020) needs to be plugged in later
No standardized query interface; each consumer implements its own search
ANN integration requires rewriting every consumer's retrieval path
Local persistence (GM-AI-P1-014) needs vector storage
EmbeddingIndexStore's JSONL is append-only with no delete support
Cannot implement idempotent upsert or soft-delete without modifying the store
Testing without remote embedding service
No way to inject fake vectors into the store
All tests require a live EmbeddingService, blocking offline CI
1.3 Design Goals
This proposal designs a VectorStore SPI for geaflow-ai, addressing the following problems:
Decouple storage from source type: A single store handles both chunk vectors and entity vectors, distinguished by metadata, not by class hierarchy.
Define a formal metadata contract: Six required fields (model_name, dimension, distance, index_version, created_at, format_version) ensure cross-store compatibility and enable fail-closed validation.
Provide reference implementations: An InMemoryVectorStore for testing and a LocalVectorStore for persistence, both validated by the same contract test suite.
Preserve backward compatibility: Existing EmbeddingIndexStore behavior is not modified; it is wrapped by EntityVectorIndex (GM-AI-P1-019) in a later issue.
1.4 Non-Goals (Scope Out)
ANN indexing: No HNSW, FAISS, or ScaNN integration. Phase 1 uses brute-force linear scan. ANN adapter is GM-AI-P1-020.
Chunk semantics: The VectorStore does not know what a "chunk" is. Chunk-specific logic (source_ref interpretation, text_hash validation) belongs in ChunkVectorIndex (GM-AI-P1-018).
Entity semantics: Similarly, entity-specific logic (vertex/edge type distinction, canonical ID resolution) belongs in EntityVectorIndex (GM-AI-P1-019).
Fusion and rerank: Score normalization, RRF, and reranking are GM-AI-P1-036 and GM-AI-P1-037.
Schema validation: Vertex/edge schema validation is GM-AI-P1-008.
Distributed storage: No multi-node replication, sharding, or consensus. Local-only for Phase 1.
Remote embedding calls: The VectorStore does not call any embedding service. It receives pre-computed vectors.
These are different abstraction layers. IndexStore is source-specific (keyed by GraphEntity); VectorStore is source-agnostic (keyed by String vectorId). The adapter between them is EntityVectorIndex (GM-AI-P1-019), which implements IndexStore and delegates to VectorStore internally.
C-2: Existing EmbeddingIndexStore must not be modified
The EmbeddingIndexStore class, its tests (if any), and its public contract remain untouched. EntityVectorIndex wraps it as a compatibility layer. This ensures no regression in existing GraphMemoryServer behavior.
C-3: All metadata fields must be validated at upsert time
Dimension mismatch, missing model_name, and missing distance metric must be detected at write time (fail-closed), not at query time. This prevents corrupted stores that silently return garbage results.
C-4: Vector IDs must be stable and deterministic
Vector IDs must not depend on wall-clock time, insertion order, or JVM object identity. They must be reproducible across runs for the same input data. This is required by the idempotency contract (GM-AI-P1-011).
2.2 Compatibility Constraints
C-5: Backward compatible — no silent behavior changes
The GraphMemoryServer.search() method currently uses instanceof checks to dispatch between EmbeddingOperator and SessionOperator. This dispatch logic must continue to work. The new VectorStore is an additional path, not a replacement.
C-6: Must work offline without remote embedding credentials
All contract tests and reference implementations must be runnable without any EmbeddingService connection. Fake embeddings (deterministic double[]) must be sufficient.
C-7: Persistence format must be forward-compatible
The format_version field is not decorative. On load, the LocalVectorStore must check it. Unknown versions must fail closed (throw exception), not skip silently.
2.3 Performance Constraints
C-8: Upsert and search must be in-memory operations
No network IO or disk IO during the hot path. Disk writes are batched and async. This aligns with the existing EmbeddingIndexStore pattern (in-memory HashMap + periodic JSONL flush).
C-9: Linear scan is acceptable for Phase 1
The search() method uses brute-force cosine similarity. The performance contract is: O(N) per query where N is the number of stored vectors. ANN acceleration is deferred to GM-AI-P1-020.
Key finding: The dispatch uses instanceof checks, not polymorphism. Adding a new index type requires modifying this method. The VectorStore SPI does not fix this dispatch problem (that is GM-AI-P1-019's job), but it provides the storage foundation that the new index types will use.
3.3 Three Missing Capabilities
Source-agnostic vector storage — current storage is keyed by GraphEntity, not by String vectorId
Metadata validation — no dimension check, no model compatibility check, no format version check
Pluggable persistence — JSONL is hardcoded; no way to swap in a different backend
publicclassVectorRecord {
/** Stable unique ID. Must not depend on wall-clock time. */privatefinalStringvectorId;
/** The embedding vector. Length must match store dimension. */privatefinaldouble[] embedding;
/** Source discriminator: "chunk", "entity", or custom type. */privatefinalStringsourceType;
/** The source identifier (chunk_id or entity_id). */privatefinalStringsourceId;
/** Additional metadata (source_ref, text_hash, extractor_version, etc.). */privatefinalMap<String, String> metadata;
// Constructor validates: vectorId non-null, embedding non-null and non-empty,// sourceType non-null, sourceId non-null.// metadata may be null (defaults to empty map).
}
Design decision: sourceType and sourceId are top-level fields (not buried in metadata) because every consumer needs to know the source kind for dispatch. The metadata map holds optional, source-specific attributes.
4.2.2 VectorQuery
publicclassVectorQuery {
/** The query embedding vector. */privatefinaldouble[] queryVector;
/** Maximum number of results to return. */privatefinalinttopK;
/** Optional metadata filters (e.g., model_name, sourceType). */privatefinalMap<String, String> filterMetadata;
// Constructor validates: queryVector non-null, topK > 0.
}
4.2.3 VectorHit
publicclassVectorHit {
/** The matched vector's ID. */privatefinalStringvectorId;
/** Similarity score (higher = more similar for cosine). */privatefinaldoublescore;
/** The full record of the matched vector. */privatefinalVectorRecordrecord;
}
4.2.4 VectorStoreMetadata
Six required fields, each with a specific engineering rationale:
Field
Type
Purpose
Failure mode if missing/wrong
model_name
String
Identifies the embedding model
Vectors from different models live in incompatible semantic spaces; cross-model queries return meaningless results
dimension
int
Vector dimensionality
Dimension mismatch causes dot() out-of-bounds or silent corruption
distance
DistanceMetric enum
COSINE, L2, DOT_PRODUCT
Different metrics produce incomparable scores; fusion (GM-AI-P1-036) would produce wrong rankings
index_version
String
Index format version
Old format may not deserialize after code upgrade
created_at
long (epoch millis)
Creation timestamp
Cannot detect stale indexes or trigger re-indexing
format_version
int
Serialization format version
Unknown format silently corrupts data; must fail closed
publicenumDistanceMetric {
COSINE,
L2,
DOT_PRODUCT
}
publicclassVectorStoreMetadata {
privatefinalStringmodelName;
privatefinalintdimension;
privatefinalDistanceMetricdistance;
privatefinalStringindexVersion;
privatefinallongcreatedAt;
privatefinalintformatVersion;
// All fields are required (no defaults). Construction fails if any is null/invalid.
}
Design decision TD-1: All metadata fields are mandatory — Optional metadata leads to downstream consumers silently assuming defaults, which produces hard-to-debug incompatibilities. A store that does not know its own dimension cannot safely upsert vectors. The cost of requiring all fields is a slightly verbose constructor; the benefit is that every store is self-describing.
4.2.5 VectorStoreException
publicclassVectorStoreExceptionextendsRuntimeException {
publicenumErrorCode {
DIMENSION_MISMATCH, // vector.length != store.dimensionMETADATA_INCOMPLETE, // required metadata field missingMODEL_MISMATCH, // query filter model_name != store model_nameFORMAT_VERSION_UNKNOWN, // unknown format_version on loadRECORD_NOT_FOUND, // vectorId does not existPERSISTENCE_ERROR// disk I/O failure
}
privatefinalErrorCodeerrorCode;
privatefinalStringdetail;
}
4.3 Core Interface
publicinterfaceVectorStore {
/** * Insert or update a single vector record. * Upsert is idempotent: same vectorId overwrites the previous record. * * @throws VectorStoreException(DIMENSION_MISMATCH) if record.embedding.length != metadata.dimension * @throws VectorStoreException(METADATA_INCOMPLETE) if required metadata fields are missing */voidupsert(VectorRecordrecord);
/** * Batch insert/update. Atomic per record; partial failure does not * roll back already-committed records. */voidupsertBatch(List<VectorRecord> records);
/** * Search for nearest vectors using the configured distance metric. * Results are ordered by score descending (best match first). * * @return empty list if no results match, never null * @throws VectorStoreException(MODEL_MISMATCH) if filterMetadata specifies * a model_name different from the store's model_name */List<VectorHit> search(VectorQueryquery);
/** * Soft-delete a vector by id. The record remains on disk but is * excluded from future search results. * * @throws VectorStoreException(RECORD_NOT_FOUND) if vectorId does not exist */voidmarkDeleted(StringvectorId);
/** * Returns metadata about this store instance. */VectorStoreMetadatagetMetadata();
/** * Release resources. Implementations must flush pending writes before returning. */voidclose();
}
4.4 Reference Implementations
4.4.1 InMemoryVectorStore
Primary purpose: contract validation and unit testing.
publicclassInMemoryVectorStoreimplementsVectorStore {
privatefinalVectorStoreMetadatametadata;
privatefinalConcurrentHashMap<String, VectorRecord> store = newConcurrentHashMap<>();
privatefinalSet<String> deletedIds = ConcurrentHashMap.newKeySet();
// search(): brute-force linear scan// - Compute cosine similarity against all non-deleted records// - Sort by score descending, return topK// - O(N) per query, acceptable for Phase 1// upsert(): validate dimension, then store.put(vectorId, record)// markDeleted(): deletedIds.add(vectorId)
}
Not persistent; resets on process restart.
Suitable for all contract tests that do not require persistence.
The search() implementation is the reference for cosine similarity scoring.
4.4.2 LocalVectorStore
Primary purpose: local persistent storage, replacing the current EmbeddingIndexStore JSONL approach.
Storage format: append-only JSONL with per-record checksum
Line format:
{"vectorId":"...", "embedding":[...], "sourceType":"...", "sourceId":"...",
"metadata":{...}, "__checksum":"...", "__deleted":false}
On startup:
1. Read all lines from JSONL file
2. Validate checksum for each line
3. Lines with checksum mismatch → quarantine (write to .quarantine file, log warning)
4. Truncated lines (invalid JSON) → quarantine
5. Build in-memory index from valid lines
6. Check format_version: unknown version → throw VectorStoreException(FORMAT_VERSION_UNKNOWN)
On upsert:
1. Validate dimension and metadata
2. Append new line to JSONL (with checksum)
3. Update in-memory index
4. If same vectorId existed: the old line is NOT modified (append-only).
The in-memory index always points to the latest line for a given vectorId.
On markDeleted:
1. Append a delete marker line: {"vectorId":"...", "__deleted":true, "__checksum":"..."}
2. Update in-memory index (remove from searchable set)
Design decision TD-2: Append-only with logical delete — In-place modification of JSONL is fragile (partial writes corrupt the file). Append-only with a delete marker ensures that crash recovery is always possible: the last occurrence of a vectorId wins. The cost is that the file grows over time; a compaction step can be added in Phase 2.
4.5 Distance Metric Implementation
publicclassDistanceUtils {
/** * Compute distance between two vectors according to the specified metric. * Returns a similarity score where higher = more similar. * * @throws VectorStoreException(DIMENSION_MISMATCH) if vectors have different lengths */publicstaticdoublecompute(double[] a, double[] b, DistanceMetricmetric) {
if (a.length != b.length) {
thrownewVectorStoreException(ErrorCode.DIMENSION_MISMATCH,
"Vector lengths differ: " + a.length + " vs " + b.length);
}
switch (metric) {
caseCOSINE: returncosineSimilarity(a, b);
caseL2: return1.0 / (1.0 + euclideanDistance(a, b)); // invert so higher = bettercaseDOT_PRODUCT: returndotProduct(a, b);
default: thrownewIllegalArgumentException("Unknown metric: " + metric);
}
}
privatestaticdoublecosineSimilarity(double[] a, double[] b) {
doubledot = 0.0, normA = 0.0, normB = 0.0;
for (inti = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
if (normA == 0.0 || normB == 0.0) return0.0;
returndot / (Math.sqrt(normA) * Math.sqrt(normB));
}
}
Activity
Sumit2342 commentedon Aug 24, 2026
Hi ,
I have gone ahead and implemented this.
I created the VectorStore SPI interface and the VectorStoreMetadata class and added the required test cases as requested.
I will open PR soon.
Sumit2342 commentedon Aug 24, 2026
I have opened PR. Please let me know if any changes, enhancement or code structure improvements is required.
Thanks.
kitalkuyo-gita commentedon Aug 25, 2026
@Sumit2342 I'm very happy to see your PR. I've been busy with work today and have a meeting tonight. I plan to review your PR tomorrow.
kitalkuyo-gita commentedon Aug 27, 2026
Hello @Sumit2342, I'm glad to see your contribution. However, this VectorStore SPI layer is an intermediate layer in the graph memory, bridging the gap between higher and lower layers. Therefore, we hope it can support different types of search abstractions. Below are some suggestions for your reference.
1. Background and Motivation
1.1 Problem Statement
The current
EmbeddingIndexStorecouples storage, index building, and similarity computation into a single monolithic class. Every layer in the pipeline is non-replaceable:This means:
GraphEntityas keys. Phase 1 requires indexing document chunks (GM-AI-P1-018), which have a fundamentally different key type (chunk_idvsGraphEntity).EmbeddingIndexStorehas zero unit tests. The coupling makes it impossible to test storage behavior in isolation.Core contradiction: Phase 1 requires two independent vector consumers —
ChunkVectorIndex(GM-AI-P1-018) andEntityVectorIndex(GM-AI-P1-019) — that share the same storage protocol but serve different source types. Without a unifiedVectorStoreSPI, these two issues will each invent their own storage, producing incompatible implementations.1.2 Quantified Impact
EmbeddingService, blocking offline CI1.3 Design Goals
This proposal designs a
VectorStoreSPI for geaflow-ai, addressing the following problems:InMemoryVectorStorefor testing and aLocalVectorStorefor persistence, both validated by the same contract test suite.EmbeddingIndexStorebehavior is not modified; it is wrapped byEntityVectorIndex(GM-AI-P1-019) in a later issue.1.4 Non-Goals (Scope Out)
ChunkVectorIndex(GM-AI-P1-018).EntityVectorIndex(GM-AI-P1-019).2. Constraints
2.1 Architectural Constraints
C-1: VectorStore must not extend IndexStore
These are different abstraction layers.
IndexStoreis source-specific (keyed byGraphEntity);VectorStoreis source-agnostic (keyed byString vectorId). The adapter between them isEntityVectorIndex(GM-AI-P1-019), which implementsIndexStoreand delegates toVectorStoreinternally.C-2: Existing EmbeddingIndexStore must not be modified
The
EmbeddingIndexStoreclass, its tests (if any), and its public contract remain untouched.EntityVectorIndexwraps it as a compatibility layer. This ensures no regression in existing GraphMemoryServer behavior.C-3: All metadata fields must be validated at upsert time
Dimension mismatch, missing model_name, and missing distance metric must be detected at write time (fail-closed), not at query time. This prevents corrupted stores that silently return garbage results.
C-4: Vector IDs must be stable and deterministic
Vector IDs must not depend on wall-clock time, insertion order, or JVM object identity. They must be reproducible across runs for the same input data. This is required by the idempotency contract (GM-AI-P1-011).
2.2 Compatibility Constraints
C-5: Backward compatible — no silent behavior changes
The
GraphMemoryServer.search()method currently usesinstanceofchecks to dispatch betweenEmbeddingOperatorandSessionOperator. This dispatch logic must continue to work. The newVectorStoreis an additional path, not a replacement.C-6: Must work offline without remote embedding credentials
All contract tests and reference implementations must be runnable without any
EmbeddingServiceconnection. Fake embeddings (deterministicdouble[]) must be sufficient.C-7: Persistence format must be forward-compatible
The
format_versionfield is not decorative. On load, theLocalVectorStoremust check it. Unknown versions must fail closed (throw exception), not skip silently.2.3 Performance Constraints
C-8: Upsert and search must be in-memory operations
No network IO or disk IO during the hot path. Disk writes are batched and async. This aligns with the existing
EmbeddingIndexStorepattern (in-memory HashMap + periodic JSONL flush).C-9: Linear scan is acceptable for Phase 1
The
search()method uses brute-force cosine similarity. The performance contract is: O(N) per query where N is the number of stored vectors. ANN acceleration is deferred to GM-AI-P1-020.3. Current State Analysis
3.1 Existing Index Architecture
IndexStoreindex/IndexStore.javagetEntityIndex(GraphEntity)EmbeddingIndexStoreindex/EmbeddingIndexStore.javaEntityAttributeIndexStoreindex/EntityAttributeIndexStore.javaIndexStoreCacheindex/IndexStoreCache.javaIVectorindex/vector/IVector.javamatch()methodEmbeddingVectorindex/vector/EmbeddingVector.javaKeywordVectorindex/vector/KeywordVector.java3.2 How Indexes Are Used in GraphMemoryServer
Key finding: The dispatch uses
instanceofchecks, not polymorphism. Adding a new index type requires modifying this method. TheVectorStoreSPI does not fix this dispatch problem (that is GM-AI-P1-019's job), but it provides the storage foundation that the new index types will use.3.3 Three Missing Capabilities
GraphEntity, not byString vectorId4. Design
4.1 Overall Architecture
4.2 Data Structures
4.2.1 VectorRecord
Design decision:
sourceTypeandsourceIdare top-level fields (not buried in metadata) because every consumer needs to know the source kind for dispatch. Themetadatamap holds optional, source-specific attributes.4.2.2 VectorQuery
4.2.3 VectorHit
4.2.4 VectorStoreMetadata
Six required fields, each with a specific engineering rationale:
model_nameStringdimensionintdot()out-of-bounds or silent corruptiondistanceDistanceMetricenumindex_versionStringcreated_atlong(epoch millis)format_versionintDesign decision TD-1: All metadata fields are mandatory — Optional metadata leads to downstream consumers silently assuming defaults, which produces hard-to-debug incompatibilities. A store that does not know its own dimension cannot safely upsert vectors. The cost of requiring all fields is a slightly verbose constructor; the benefit is that every store is self-describing.
4.2.5 VectorStoreException
4.3 Core Interface
4.4 Reference Implementations
4.4.1 InMemoryVectorStore
Primary purpose: contract validation and unit testing.
search()implementation is the reference for cosine similarity scoring.4.4.2 LocalVectorStore
Primary purpose: local persistent storage, replacing the current EmbeddingIndexStore JSONL approach.
Design decision TD-2: Append-only with logical delete — In-place modification of JSONL is fragile (partial writes corrupt the file). Append-only with a delete marker ensures that crash recovery is always possible: the last occurrence of a vectorId wins. The cost is that the file grows over time; a compaction step can be added in Phase 2.
4.5 Distance Metric Implementation
Sumit2342 commentedon Aug 27, 2026
Thanks @kitalkuyo-gita for detailed design document.
I have already started refactoring my implementation to match this exact blueprint.
I will push the updated code to my PR for your review.
Thanks again for the review.
Sumit2342 commentedon Aug 28, 2026
Hi @kitalkuyo-gita ,
I have updated my PR. Can you please review it again and let me know if any other changes or enhancement is required.
Thanks.