Repository avatar
Other Tools
v1.5.1
active

synapse-memory

io.github.721189/synapse-memory

Tenant-scoped memory and agent-run tools over the authenticated Synapse Memory API.

Documentation

Synapse Memory

Self-hostable, tenant-aware memory infrastructure for AI applications.

Field-level encryption on content at rest (the content_plain search projection is plaintext — see SECURITY.md) · Hybrid retrieval (BM25 + pgvector HNSW + RRF) · Token-budgeted context packing (0/1 Knapsack DP) Database-level tenant isolation (PostgreSQL RLS) · Fail-closed paths are covered by tests · PyPI 1.5.1 published under Apache 2.0; the older 1.4.0 artifact retains its original proprietary terms

XERJ Corpus Hub contributor CI/CD Pipeline PyPI version Python Node.js PostgreSQL Tests Security License: Apache 2.0


Table of Contents


1. Executive Summary

Synapse Memory (v1.5.1) is a persistent, encrypted, multi-tenant memory layer that solves the statelessness of LLM APIs. It ingests text, embeds it, deduplicates it, stores it encrypted, and later returns only the most relevant context that fits a finite token budget — fused across lexical and dense retrieval, decayed by recency and usage, and packed by dynamic programming instead of naive truncation.

StatusPython SDK 1.5.1 was published to PyPI on 2026-12-01 under Apache 2.0. Its MCP server metadata was successfully published to the official MCP Registry as io.github.721189/synapse-memory. The older 1.4.0 artifact retains its original proprietary terms. CI and release checks passing are not independent production sign-off: workload-specific validation, an independent security review, and customer usage remain outstanding.
SurfacesHTTP engine (FastAPI, :8008) · Node gateway + React dashboard (:3000) · Python SDK (synapse-memory-engine 1.5.1 on PyPI) · MCP server (synapse-mcp / synapse-memory-engine)
StoragePostgreSQL 16 + pgvector HNSW (production) · SQLite (single-node dev) — both with Fernet field encryption
IntegrationsLangChain · LlamaIndex · raw HTTP (any language)
DeploymentDocker Compose (4 services) · Kubernetes Helm chart (split engine/gateway + HPA) · bare uvicorn
GuaranteesDatabase-level tenant isolation (RLS) · fail-closed (no silent fallbacks) · least-privilege DB roles · SHA-pinned CI
Quality gatesflake8 · mypy (26 files) · bandit · Trivy (CRITICAL,HIGH) · TruffleHog · 150+ pytest · live pgvector integration suite

2. The Problem

Every POST /v1/chat/completions call is independent. The model has no memory of prior interactions, and applications that bolt on naive "chat history" hit five hard failure modes:

#RequirementNaive approach fails because…Synapse Memory solution
1Retrieve relevant context at scaleBrute-force similarity scan degrades linearly; keyword-only search misses semantic matchesHybrid search: BM25 (PostgreSQL FTS) + HNSW vector index in parallel, fused with Reciprocal Rank Fusion (k=60)
2Fit context into a finite windowNaive truncation drops the most valuable facts for the current prompt0/1 Knapsack DP packs memories by value = relevance × 1000, weight = token_cost — O(n·budget)
3Manage memory lifecycleStale facts never die; duplicates accumulate; confidence never evolvesEbbinghaus decay S = R × D composition, RLAIF feedback multipliers, dual-stage dedup (Jaccard + cosine ≥ 0.85)
4Isolate tenantsAPI-level WHERE tenant_id = ? is one bug away from a cross-tenant data leakPostgreSQL FORCE ROW LEVEL SECURITY keyed on app.current_tenant plus explicit SQL predicates — proven by live least-privilege role tests
5Protect data at restTLS protects transit only; a DB dump or leaked backup exposes everythingFernet (AES-128-CBC + HMAC-SHA256) field-level encryption on content, fail-safe on key loss, keys from env/file/KMS. Scope: the content_plain search projection (and the tsvector/embedding derivatives built from it) is stored in plaintext so lexical/FTS search works — a DB dump or backup therefore still exposes memory text. Rely on DB access controls + volume/backup encryption for that surface, or disable the projection (SYNAPSE_STORE_SEARCHABLE_PLAINTEXT=false, lexical search unavailable). Details and residual-risk treatment: SECURITY.md.

3. Architecture

3.1 System Topology

flowchart TB
    subgraph Clients["Clients"]
        AGENT["Agent / RAG pipeline<br/>(Python SDK, HTTP, LangChain, LlamaIndex)"]
        DASH["React dashboard / playground"]
    end

    subgraph Gateway["Gateway — Node 20+ / Express :3000"]
        PROXY["API proxy /api/*"]
        RBACGW["Auth header passthrough<br/>CORS allowlist · fail-closed readiness"]
    end

    subgraph Engine["Cognitive Engine — Python 3.10+ / FastAPI :8008"]
        AUTH["SecurityManager<br/>SHA-256 keys · RBAC scopes · audit log"]
        RL["RateLimiter<br/>Redis sliding window / in-process"]
        MM["MemoryManager<br/>validation · lifecycle · feedback"]
        RET["HybridSearch<br/>BM25 + HNSW + RRF k=60"]
        PACK["KnapsackPacker<br/>0/1 DP O(n·budget)"]
        DECAY["DecayEngine<br/>S = R x D · RLAIF"]
        DEDUP["Deduplicator<br/>Jaccard + cosine >= 0.85"]
        ENC["Fernet field encryption<br/>AES-128-CBC + HMAC-SHA256"]
        METRICS["/metrics /liveness /readiness /health"]
    end

    subgraph Data["State"]
        PG[("PostgreSQL 16 + pgvector<br/>HNSW index · RLS · content_plain")]
        SQLITE[("SQLite — dev only")]
        REDIS[("Redis 7 — rate limit<br/>+ query cache (optional)")]
    end

    subgraph LLM["Embedding providers"]
        LOCAL["all-MiniLM-L6-v2 (384-d)"]
        OPENAI["OpenAI"]
        GEMINI["Gemini"]
    end

    DASH --> PROXY
    AGENT -->|"HTTP + X-Synapse-API-Key"| PROXY
    PROXY --> RBACGW
    RBACGW --> AUTH
    AUTH --> RL --> MM
    MM --> RET
    RET --> PACK --> DECAY
    MM --> DEDUP --> ENC
    ENC --> PG
    MM --> SQLITE
    RL -.-> REDIS
    RET --> LOCAL
    RET --> OPENAI
    RET --> GEMINI

    style Engine fill:#1e1b4b,stroke:#6366f1,color:#fff
    style Data fill:#312e81,stroke:#818cf8,color:#fff
    style Gateway fill:#064e3b,stroke:#34d399,color:#fff

3.2 Ingestion Pipeline

sequenceDiagram
    participant App as Application
    participant GW as Gateway :3000
    participant API as Engine :8008
    participant DB as Encrypted Store (pgvector)

    App->>GW: POST /api/memories/create {content, category}
    GW->>API: proxied POST /ingest (+ X-Synapse-API-Key)
    API->>API: Auth: SHA-256 key hash, scope memories:write, tenant bind
    API->>API: Rate limit (Redis sorted-set sliding window, 120 req/min)
    API->>API: Validate (Pydantic strict limits, content <= 32000 chars)
    API->>API: Embed (384-d MiniLM or provider-specific)
    API->>API: Encrypt content with Fernet (content_plain search projection)
    API->>API: Dedup: Jaccard token screen then cosine verify (>= 0.85)
    alt Duplicate found
        API->>API: MERGE (confidence update, supersede chain)
    else New memory
        API->>DB: INSERT (ciphertext + embedding + tsvector)
        DB-->>DB: RLS check via app.current_tenant
    end
    API-->>GW: {success: true, data: {id, status, token_cost}, request_id}
    GW-->>App: 201 Created

3.3 Retrieval Pipeline

sequenceDiagram
    participant App as Application
    participant API as Engine :8008
    participant DB as pgvector (HNSW + FTS)

    App->>API: POST /query {prompt, max_token_budget: 1500}
    API->>API: Auth + tenant bind + rate limit
    par Dense channel
        API->>DB: embedding <=> query (HNSW, top-100)
        DB-->>API: ranked vector hits
    and Lexical channel
        API->>DB: search_vector @@ plainto_tsquery (BM25, top-100)
        DB-->>API: ranked keyword hits
    end
    API->>API: Dedup by id across pools
    API->>API: RRF fusion k=60: COALESCE score = sum 1/(k+rank)
    API->>API: Temporal decay: relevance x e^(-t/S), S = R x D
    API->>API: Feedback multiplier (RLAIF confidence)
    API->>API: Knapsack DP: max sum(value) s.t. sum(weight) <= budget
    API-->>App: {fused_context, injected_nodes, retrieval_score, decay_multiplier}
    Note over API,DB: Every row pre-filtered by RLS + explicit tenant_id predicate

3.4 Deployment Topologies

flowchart LR
    subgraph DEV["Development — single node"]
        E1["Engine (SQLite)"]
        G1["Gateway"]
        G1 --> E1
    end

    subgraph PROD["Production — split images, external state"]
        direction TB
        LB["Load balancer / Ingress"]
        G2["Gateway Deployment xN (HPA 3-15)"]
        E2["Engine Deployment xN (HPA 3-15)"]
        PGR[("External pgvector PostgreSQL<br/>volume encryption at rest")]
        R2[("Redis — distributed rate limit")]
        LB --> G2 --> E2
        E2 --> PGR
        E2 -.-> R2
    end

    DEV -.->|"docker compose up -d"| PROD
AspectDev topologyProduction topology
Imagescombined Dockerfile (demo only)split Dockerfile.engine + Dockerfile.gateway
StorageSQLite fileExternal pgvector, RLS enforced
DB rolessingle owner role, SYNAPSE_APPLY_DB_SCHEMA=truemigrate-then-run: migration role (DDL) + synapse_app runtime role (DML only, NOBYPASSRLS)
Rate limitingin-process windowRedis sorted-set window across all replicas
Secrets.env fileKubernetes Secret / KMS / Vault — never ConfigMap
Demo routesENABLE_DEMO_ROUTES=truealways false

3.5 Fail-Closed Request Lifecycle

flowchart TD
    REQ["Incoming request"] --> AUTH{"API key valid<br/>+ scope + tenant?"}
    AUTH -->|no| GEN403["HTTP 403 generic<br/>'Authentication failed.'<br/>detail to audit log"]
    AUTH -->|yes| RLIM{"Rate limit<br/>120 req/min per key+path"}
    RLIM -->|exceeded| GEN429["HTTP 429 +<br/>synapse_rate_limit_rejections_total"]
    RLIM -->|ok| DB{"Database reachable?"}
    DB -->|no| GEN503["HTTP 503 — never fake success<br/>/liveness OK, /readiness 503"]
    DB -->|yes| SCHEMA{"SYNAPSE_APPLY_DB_SCHEMA=false<br/>and schema missing?"}
    SCHEMA -->|yes| REFUSE["Refuse to start<br/>no silent in-memory fallback"]
    SCHEMA -->|no| OK["Process request<br/>{success: true, data, request_id}"]

    style GEN403 fill:#7f1d1d,color:#fff
    style GEN429 fill:#78350f,color:#fff
    style GEN503 fill:#7f1d1d,color:#fff
    style REFUSE fill:#7f1d1d,color:#fff
    style OK fill:#14532d,color:#fff

4. Core Engines

EngineAlgorithmComplexityKey parameters & behavior
HybridSearchBM25 (PostgreSQL FTS) + cosine (HNSW) fused by Reciprocal Rank FusionO(n) per channelk=60; COALESCE-safe per-channel scores (NULL channel never zeroes a hit); top-100 per pool, dedup by id before fusion
KnapsackPacker0/1 dynamic programming with greedy fallbackO(n · budget)value = relevance × 1000, weight = token_cost; greedy kicks in when n × budget > 2M; hard cap max_token_budget ≤ 8000
DecayEngineEbbinghaus forgetting curve × usage strengthO(1) per noderelevance × e^(−t/S) with S = R × D composition (retention × access); S = 86400 × (1 + access_count × 0.45); floor at 0.10; RLAIF feedback adjusts confidence
DeduplicatorTwo-stage: lexical screen → dense verifyO(n) per insertJaccard token overlap prefilter, cosine ≥ 0.85 confirms; merges confidence + supersede chain instead of discarding
SecurityManagerSHA-256 key hashing + Fernet + scope RBACO(1) per requestKeys hashed at rest (never stored/returned plaintext); scopes memories:read/write/delete, admin; tenant from key or X-Tenant-ID; full audit trail
RateLimiterRedis sorted-set sliding window (Lua) / in-process fallbackO(log n)120 req/min per key+path (tunable); Redis outage degrades to per-replica windows — never fails requests
ThreadedConnectionPoolThread-safe pool with acquire timeoutO(1)Rollback-on-return (no transaction leakage); pool_stats() exported to /metrics; ThreadedConnectionPool for multi-worker safety
PGVectorMemoryStorepgvector + HNSW + FORCE ROW LEVEL SECURITYindex-assistedExplicit tenant_id predicate in addition to RLS; fail-closed on errors; migrate-then-run aware (apply_schema=False)
SQLiteMemoryStoreFile-backed SQLiteO(n)Single-node development only; app-level tenant scoping; same encryption and dedup contracts

Formulas at a glance

RRF score       = Σ  1 / (60 + rank_channel)          over available channels (COALESCE-safe)
Decay           = relevance × e^(−t / S),  S = R × D
Confidence'     = confidence × feedback_multiplier      (RLAIF, clamped)
Pack objective  = max Σ value(m)  s.t.  Σ token_cost(m) ≤ budget,  m ∈ candidates
Dedup merge     = Jaccard ≥ threshold  AND  cosine ≥ 0.85  →  merge (confidence ↑, supersede)

5. Feature Matrix

CategoryCapabilityStatus
RetrievalHybrid BM25 + HNSW dense search with RRF fusion (k=60)✅
Token-budgeted context packing via 0/1 Knapsack DP (greedy fallback)✅
Temporal decay S = R × D composition preserved through /query✅
RLAIF feedback loop (POST /feedback adjusts confidence)✅
Dual-stage semantic deduplication with merge/supersede✅
SecurityFernet field-level encryption (AES-128-CBC + HMAC-SHA256) on content✅
SHA-256 hashed API keys, scope RBAC, generic auth errors (no reason leakage)✅
PostgreSQL FORCE ROW LEVEL SECURITY + explicit tenant predicates✅
Least-privilege DB roles (DML-only runtime role, NOBYPASSRLS, verified in CI)✅
PII scrubbing (emails, phones, SSNs, cards, sk-* keys, Aadhaar, PAN)✅
GDPR right-to-erasure (/api/security/gdpr-delete with audited deleted_count)✅
Distributed rate limiting (Redis) + audit log export (SIEM-ready)✅
ReliabilityFail-closed: 503 on DB outage, refuse-to-start on missing schema✅
Liveness vs readiness probes (DB-independent vs DB-backed)✅
Thread-safe connection pool, rollback-on-return, pool metrics✅
Idempotent forward-only migrations (schema v4), backup/restore drill✅
Load/resilience suite (concurrency, outages, restarts, bursts — 17 tests)✅
OperationsLive Prometheus /metrics (requests, p50/p95, auth, pool, packing)✅
Split Docker images + Trivy scanning; Helm chart with HPA + Ingress✅
Compose health gating; ops runbook; branch-protection spec✅
EcosystemPython SDK SynapseClient (typed, retries, envelope-aware)✅
LangChain & LlamaIndex integrations✅
React dashboard (retrieval, decay, knapsack, security, graph tabs)✅
Docker Compose (4 services) + Kubernetes Helm chart✅

6. Quick Start

6.1 Fastest local start (SQLite, no external services)

This path is for evaluating the API on your own machine. It uses SQLite and the built-in deterministic hash embedder so you do not need PostgreSQL, an API key, or an embedding-provider account. The hash embedder is not semantic; use a real embedding provider for meaningful semantic retrieval and do not use this configuration as a production deployment.

Create a virtual environment and install the published SDK (which also includes the FastAPI engine):

python -m venv .venv
# macOS/Linux:
source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1

python -m pip install --upgrade pip
python -m pip install synapse-memory-engine

Start the engine in terminal 1:

export SYNAPSE_STORAGE_BACKEND=sqlite
export SYNAPSE_SQLITE_DB_PATH=./synapse_memory.db
python -m uvicorn synapse_memory.api.fastapi_server:app --host 127.0.0.1 --port 8008

On Windows PowerShell, set the two variables with $env:SYNAPSE_STORAGE_BACKEND="sqlite" and $env:SYNAPSE_SQLITE_DB_PATH="./synapse_memory.db" before running Uvicorn.

In terminal 2, with the same virtual environment active, save this as quickstart.py and run python quickstart.py:

from synapse_memory import SynapseClient

with SynapseClient("http://127.0.0.1:8008", tenant_id="local-dev") as client:
    saved = client.create_memory(
        "The project uses PostgreSQL in production and SQLite for local demos.",
        category="fact",
    )
    print(f"Saved memory: {saved.id} ({saved.status})")

    result = client.retrieve("Which database is used for local demos?")
    print("Retrieved context:")
    print(result.fused_context or "(No context returned; check engine logs.)")

The first run may create a local .synapse_key file for encryption. Keep that file safe and stable while the database exists: losing or changing the key can make existing encrypted content unreadable. Do not commit the key or local database to source control.

To stop the engine, press Ctrl+C in terminal 1. See the dedicated quickstart for production prerequisites, curl commands, and troubleshooting.

6.2 Docker Compose (recommended — full production-shaped stack)

git clone https://github.com/721189/Synapse-Memory.git
cd Synapse-Memory
cp deploy/.env.example deploy/.env

# Generate five distinct secrets for deploy/.env:
python -c "import secrets; print('syn_live_' + secrets.token_hex(24))"           # SYNAPSE_API_KEY
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"  # SYNAPSE_ENCRYPTION_KEY
python -c "import secrets; print(secrets.token_urlsafe(32))"                     # POSTGRES_PASSWORD (bootstrap superuser)
python -c "import secrets; print(secrets.token_urlsafe(32))"                     # SYNAPSE_ADMIN_DB_PASSWORD (migration role)
python -c "import secrets; print(secrets.token_urlsafe(32))"                     # SYNAPSE_APP_DB_PASSWORD (runtime role)

# In deploy/.env, also set GEMINI_API_KEY if SYNAPSE_EMBEDDING_PROVIDER=gemini
# (the default), or OPENAI_API_KEY if selecting the OpenAI provider.
# Keep all five generated secrets different. Compose fails closed if any
# required value is missing; the API key and encryption key are not passwords
# for the PostgreSQL bootstrap, migration, or runtime database roles.

docker compose -f deploy/docker-compose.yml up -d

Clean-install path (empty volume). The engine connects as synapse_app, a least-privilege DML-only runtime role that deliberately cannot create the schema. docker compose up therefore runs a one-shot db-provision service first: it creates/repairs the runtime role, applies the schema migrations as the admin role, and verifies the NON-owner / NOBYPASSRLS invariant — then exits 0, at which point the engine starts. No manual SQL step is needed for Compose.

The equivalent manual step for a managed database (or before a Helm install):

# Bootstrap credentials remain separate from the migration and runtime roles.
export SYNAPSE_BOOTSTRAP_DATABASE_URL="postgresql://postgres:<bootstrap-password>@host:5432/synapse_cognitive"
export SYNAPSE_MIGRATION_DATABASE_URL="postgresql://synapse_admin:<migration-password>@host:5432/synapse_cognitive"
export SYNAPSE_API_KEY="syn_live_your_generated_key"
export SYNAPSE_ENCRYPTION_KEY="your_generated_fernet_key"
export SYNAPSE_ADMIN_DB_PASSWORD="<migration-password>"
export SYNAPSE_APP_DB_PASSWORD="<runtime-password>"
python scripts/provision_db_roles.py \
  --runtime-role synapse_app --admin-role synapse_admin \
  --runtime-password "$SYNAPSE_APP_DB_PASSWORD" \
  --admin-password "$SYNAPSE_ADMIN_DB_PASSWORD" --apply-migrations
ServicePortHealth probe
db-provision (one-shot roles + migrations)—exits 0
synapse-memory-engine (FastAPI)internal :8008GET /readiness
synapse-memory-gateway (dashboard + proxy):3000GET /api/ready
postgres-pgvector (pg16)internal :5432pg_isready
redis-state (Redis 7)internal :6379redis-cli ping

All health checks are gated: the gateway waits for the engine, the engine waits for db-provision to complete successfully, PostgreSQL and Redis. No service starts against an unhealthy or unmigrated dependency.

6.3 Python SDK (5-minute path)

pip install "synapse-memory-engine[pgvector]"   # production backend
# or: pip install synapse-memory-engine         # SQLite dev backend only
from synapse_memory import SynapseClient, SynapseError

with SynapseClient("http://127.0.0.1:8008",
                   api_key="syn_live_your_key",
                   tenant_id="acme") as client:
    created = client.create_memory(
        "The deploy password rotates every 90 days.", category="fact"
    )
    print(created.id, created.status)

    result = client.retrieve("how often does the deploy password rotate?")
    print(result.fused_context)          # packed context within token budget

    try:
        client.retrieve("")
    except SynapseError as e:
        print("handled:", e, "retryable:", e.retryable)

6.4 curl

# Ingest
curl -X POST http://localhost:8008/ingest \
  -H "X-Synapse-API-Key: $SYNAPSE_API_KEY" \
  -H "X-Tenant-ID: acme" \
  -H "Content-Type: application/json" \
  -d '{"content": "User prefers TypeScript for backend", "category": "preference"}'

# Query (token-budgeted packed context)
curl -X POST http://localhost:8008/query \
  -H "X-Synapse-API-Key: $SYNAPSE_API_KEY" \
  -H "X-Tenant-ID: acme" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "What language does the user prefer?", "max_token_budget": 1500}'

6.5 Local development (SQLite, no dependencies)

pip install -e "sdk/python[all,dev]"
PYTHONPATH=sdk/python uvicorn synapse_memory.api.fastapi_server:app --port 8008
# Omit DATABASE_URL entirely → SQLite backend, app-level tenant scoping.

7. Deployment

7.1 Docker Compose

docker compose -f deploy/docker-compose.yml up -d          # start
docker compose -f deploy/docker-compose.yml ps             # all services healthy?
curl -s localhost:3000/api/ready; curl -s localhost:8008/readiness

Key env vars live in deploy/.env (copy from deploy/.env.example). Compose requires five distinct values: SYNAPSE_API_KEY, SYNAPSE_ENCRYPTION_KEY, bootstrap-superuser POSTGRES_PASSWORD, migration-role SYNAPSE_ADMIN_DB_PASSWORD, and runtime-role SYNAPSE_APP_DB_PASSWORD. Also set the API key for the selected embedding provider (the default is Gemini). These DB credentials must not be reused.

7.2 Kubernetes (Helm)

The chart deploys only engine + gateway workloads — PostgreSQL is a documented external dependency (never installed by the chart).

# 1. Provision pgvector PostgreSQL (managed service or pgvector/pgvector:pg16)
# 2. Create the credentials Secret (see values.yaml → secrets.existingSecret):
kubectl create secret generic synapse-credentials \
  --from-literal=SYNAPSE_API_KEY=... \
  --from-literal=SYNAPSE_ENCRYPTION_KEY=... \
  --from-literal=SYNAPSE_APP_DB_PASSWORD=... \
  --from-literal=GEMINI_API_KEY=... \
  --from-literal=REDIS_PASSWORD=...
# If using OpenAI embeddings, supply OPENAI_API_KEY instead of GEMINI_API_KEY.
# Do not place bootstrap or migration-role credentials in this application Secret.

# 3. Migrate-then-run (see 7.3), then install:
helm install synapse deploy/helm-chart \
  --set config.nodeEnv=production \
  --set config.dbHost=<pgvector-host> \
  --set config.applyDbSchema=false \
  --set config.dbUser=synapse_app
Helm resourceDetail
Deploymentsengine + gateway, split scaling, non-root containers
Servicescluster-IP per workload; gateway derives PYTHON_ENGINE_URL from the release fullname
HPAminReplicas 3 / maxReplicas 15, CPU+memory 80%
Ingressoptional; TLS termination at ingress recommended
Secretsvia existing Secret — never ConfigMap; kubelet $(VAR) expansion ordering guarded
Chart version0.3.0 (app 1.3.1) — chart version ≠ app version, see Chart.yaml

7.3 Migrate-then-run: least-privilege database roles

sequenceDiagram
    participant Op as Operator
    participant Script as provision_db_roles.py
    participant PG as PostgreSQL
    participant Eng as Engine (synapse_app)

    Op->>Script: DATABASE_URL=<bootstrap admin DSN> run script
    Script->>PG: CREATE synapse_admin (DDL) + synapse_app (DML only)
    Script->>PG: ALTER ROLE synapse_app NOBYPASSRLS NOSUPERUSER NOCREATEDB
    Script->>PG: Verify invariant - exit non-zero if violated
    Op->>PG: Apply schema migration AS synapse_admin (DDL)
    Op->>Script: Re-run script (grants DML on new tables - idempotent)
    Op->>Script: --verify-only (must exit 0)
    Op->>Eng: Start with synapse_app DSN, SYNAPSE_APPLY_DB_SCHEMA=false
    Eng->>PG: SELECT/INSERT/UPDATE/DELETE only - cannot execute DDL
    Eng->>Eng: Refuses to start if schema is missing (fail-closed)
DATABASE_URL=postgresql://<bootstrap-admin>@<host>/<db> python scripts/provision_db_roles.py \
  --runtime-role synapse_app --admin-role synapse_admin \
  --runtime-password "$SYNAPSE_APP_DB_PASSWORD" \
  --admin-password   "$SYNAPSE_ADMIN_DB_PASSWORD"
python scripts/provision_db_roles.py --verify-only   # must exit 0

7.4 Version compatibility

ComponentVersionNotes
Python SDK (synapse-memory-engine)1.5.1 publishedPublished 2026-12-01 under Apache 2.0; includes the MCP stdio server and official MCP Registry metadata. Version 1.4.0 retains its original proprietary terms.
HTTP API compatv1canonical {success, data, request_id} envelope; /api/* aliases stable
Engine / gateway imagesv1.3.1 default image tagsPyPI publication does not publish container images; Helm defaults remain pinned to the last image tag
Helm chart0.3.0 (app 1.3.1)chart version ≠ app version; see Chart.yaml
Schemav7 ledgerforward-only; v7 adds memory provenance, temporal validity, and retraction metadata
Python3.10 / 3.11 / 3.12CI-tested matrix
Node.js≥ 20.19 (20.x, 22.x in CI)gateway build matrix
PostgreSQL16 + pgvector ≥ 0.2HNSW index, tsvector, RLS

8. Configuration Reference

Single source of truth: deploy/.env.example (compose) and deploy/helm-chart/values.yaml (Kubernetes).

Secrets (never commit, never in ConfigMap)

VariableRequiredDescription / generation
SYNAPSE_API_KEY✅Root API key bootstrapped on first start (hashed at rest). python -c "import secrets; print('syn_live_'+secrets.token_hex(24))"
SYNAPSE_ENCRYPTION_KEY✅Fernet 32-byte urlsafe-base64 data-at-rest key. python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())". In prod source from KMS/Vault
POSTGRES_PASSWORD✅ (Compose)Bootstrap PostgreSQL superuser password used only to install extensions and provision roles; not the API runtime password
SYNAPSE_ADMIN_DB_PASSWORD✅ (Compose/provisioning)Password for the distinct non-superuser migration role (SYNAPSE_DB_ADMIN_ROLE); do not expose to API pods
SYNAPSE_APP_DB_PASSWORD✅ (Compose/Helm runtime)Password for the DML-only, non-owner runtime role (usually synapse_app) used by DATABASE_URL
REDIS_PASSWORDoptionalRedis auth (may be empty)
GEMINI_API_KEY / OPENAI_API_KEYrequired for selected providerEmbedding-provider key; default provider is Gemini

Storage & schema

VariableDefaultDescription
SYNAPSE_STORAGE_BACKENDpgvectorpgvector (team/production) or sqlite (single-node dev)
DATABASE_URL—pgvector DSN. When set with SYNAPSE_ALLOW_DB_FALLBACK=false, outages fail closed
SYNAPSE_SQLITE_DB_PATH/data/synapse_memory.dbSQLite path (dev only)
SYNAPSE_APPLY_DB_SCHEMAtruetrue = engine owns DDL (dev); false = migrate-then-run least-privilege production mode — engine refuses to start if schema missing
SYNAPSE_ALLOW_DB_FALLBACKfalsetrue ONLY for local dev — silently degrades to in-memory (data loss on restart)
SYNAPSE_APP_DATABASE_URL—Runtime-role DSN for provisioned synapse_app

Networking & gateway

VariableDefaultDescription
GATEWAY_PORT / ENGINE_PORT3000 / 8008Published ports
PYTHON_ENGINE_URLhttp://127.0.0.1:8008Gateway → engine target (Helm derives it from the release fullname)
ALLOWED_ORIGINShttp://localhost:3000,...Comma-separated CORS allowlist; ALLOW_ALL_CORS=true is dev-only
ENABLE_DEMO_ROUTESfalseMust be false in production — gates simulated demo endpoints
NODE_ENVproductionRuntime mode

Limits, rate limiting & tuning

VariableDefaultDescription
RATE_LIMIT_PER_MIN120Per key + path on mutating/heavy-retrieval routes
RATE_LIMIT_WINDOW_SECONDS60Sliding-window length
REDIS_URL—When set: distributed Redis sorted-set window across ALL replicas; unset: in-process per replica. Redis outage never fails requests
TOKEN_BUDGET_MAX1500Default knapsack budget cap (hard limit 8000)

Embeddings (optional)

VariableDefaultDescription
SYNAPSE_EMBEDDING_PROVIDERunset: dev deterministic; Compose/Helm: geminigemini | openai | sentence-transformers; deterministic/local/hash is development/test only
SYNAPSE_EMBEDDING_MODELall-MiniLM-L6-v2Sentence-transformers model name
SYNAPSE_EMBEDDING_DIMENSIONprovider-dependentGemini: 3072; OpenAI text-embedding-3-small: 1536; MiniLM: 384; deterministic: 128. Gemini/OpenAI can request supported output widths; schema and query vectors must match.

Database roles (migrate-then-run)

VariableDefaultDescription
SYNAPSE_DB_RUNTIME_ROLEsynapse_appDML-only runtime role (non-owner, NOBYPASSRLS)
SYNAPSE_DB_ADMIN_ROLEsynapse_adminNon-superuser schema-migration role (DDL only)
SYNAPSE_DB_RUNTIME_ROLEsynapse_appNon-owner, DML-only API runtime role; must not own tables or have BYPASSRLS
SYNAPSE_BOOTSTRAP_DATABASE_URL—Bootstrap/superuser DSN for extension installation and role provisioning only
SYNAPSE_MIGRATION_DATABASE_URL—Separate DSN used for schema migrations; must not be the bootstrap role
SYNAPSE_APP_DB_PASSWORD / SYNAPSE_ADMIN_DB_PASSWORD—Distinct passwords for runtime and migration roles

9. HTTP API Overview

Full contract (every route, schema bound, and error code): docs/api-reference.md.

Envelope — every response carries a request id for end-to-end tracing (pass X-Request-ID):

{"success": true,  "data": {...},           "request_id": "…"}
{"success": false, "error": "…",            "request_id": "…"}

Auth: X-Synapse-API-Key: <key> (or Authorization: Bearer <key>) on all endpoints except unauthenticated probes (/liveness, /readiness, /health, /metrics). Optional X-Tenant-ID participates in tenant resolution.

Canonical vs alias paths

Canonical pathAliasesMethod
/api/memories/api/memories/listGET
/api/memories/create/ingest, /api/memories/addPOST
/api/memories/query/query, /api/retrieval/knapsack-packPOST
/api/security/scrub/api/security/scrub-piiPOST

Permission matrix (summary)

ScopeEndpoints
(none — probes)GET /liveness, /readiness, /health, /metrics
memories:readlist, query, scrub
memories:writeingest, bulk (≤100 items, 500KB), feedback
memories:deletedelete, clear, gdpr-delete
memories:trustassign medium, high, or authoritative provenance; platform-admin-only delegation
adminkey create/list/revoke/rotate, audit read/export/prune; does not imply memories:trust

Error taxonomy

CodeMeaningRetry?
400Semantic error (empty content, admin tenant missing)no
401/403Auth failure — always generic "Authentication failed."; detail in audit log; tenant mismatch = "Tenant mismatch."no
404Unknown resource idno
413Bulk payload oversizeno
422Pydantic schema violation (field-level detail)no
429Rate limit — "Rate limit exceeded. Retry after 60s."yes, after 60s
503DB/provider unavailable — fail-closed, never fake successyes, with backoff

10. SDK & Framework Integrations

10.1 Python client (SynapseClient)

Typed, envelope-aware, with retries and retryable classification on SynapseError.

MethodSignatureReturns
create_memory(content, category="interaction", confidence=0.95)CreateResult(id, status, …)
retrieve(query, max_tokens=1500)QueryResult(fused_context, injected_nodes, …)
list_memories(limit=50, offset=0)paginated dict
delete_memory(memory_id)dict
feedback(memory_id, feedback_type)dict (adjusts confidence → decay)
health / readiness()probe dicts
close()context manager (with supported)—

Errors: SynapseError(message, status=?, retryable=?) — retryable=True on 429/5xx so callers can back off safely; 400/403/404 are terminal.

pip install "synapse-memory-engine[all]"   # everything: pgvector, langchain, llamaindex, redis, local models

Optional extras: [pgvector], [local-models], [redis], [mcp], [langchain], [llamaindex], [all], [dev].

10.2 LangChain

from synapse_memory.integrations.langchain import SynapseLangChainMemory

memory = SynapseLangChainMemory(
    tenant_id="acme", memory_manager=manager, searcher=searcher,
    decay=decay, packer=packer, embedder=embedder,
)
memory.save_context(
    inputs={"input": "Capital of France?"},
    outputs={"output": "Paris"},
)

10.3 LlamaIndex

from synapse_memory.integrations.llamaindex import SynapseLlamaIndexMemory
# Role is normalized ("memory"/"llm") internally — construct with the same
# manager/searcher/decay/packer/embedder wiring as LangChain.

10.4 Model Context Protocol (MCP)

An optional stdio MCP server exposes tenant-scoped memory retrieval/creation and metadata-only agent-run inspection through the authenticated HTTP API. It does not access storage directly or accept tenant overrides. Install the optional extra from the published SDK (Python 3.11 or newer):

python -m pip install "synapse-memory-engine[mcp]==1.5.1"
export SYNAPSE_BASE_URL="http://127.0.0.1:8008"
export SYNAPSE_API_KEY="YOUR_SCOPED_API_KEY"
export SYNAPSE_TENANT_ID="your-tenant"
synapse-mcp

See MCP server setup and security for the tool list, required API scopes, client configuration, and limitations. The integration is included in the published 1.5.1 package and registered as io.github.721189/synapse-memory in the official MCP Registry.

10.5 Other languages

Any HTTP client works — the contract is just the envelope + API key header (see docs/api-reference.md). The Node gateway (server.ts) also exposes /api/* aliases consumed by the React dashboard.

11. Security Model

Full OWASP API Top 10 (2023) assessment: docs/security-review.md · Policy & disclosure: SECURITY.md.

flowchart TD
    subgraph L1["Layer 1 — Edge"]
        TLS["TLS termination (ingress)"]
        CORS["CORS allowlist"]
        RL["Rate limit 120 req/min/key<br/>fail-closed"]
    end
    subgraph L2["Layer 2 — Authentication & authorization"]
        KEY["API key: SHA-256 at rest<br/>never stored or echoed plaintext"]
        SCOPE["RBAC scopes: memories:read/write/delete, admin"]
        TEN["Tenant resolution<br/>resolve_tenant rejects mismatch (403)"]
        AUD["Audit log: every auth event<br/>+ destructive action"]
    end
    subgraph L3["Layer 3 — Data"]
        ENC["Fernet field encryption (content)<br/>AES-128-CBC + HMAC-SHA256"]
        PII["PII scrubber (pre-ingest)"]
        RLS["PostgreSQL FORCE ROW SECURITY<br/>+ explicit tenant_id predicate"]
        ROLE["DML-only runtime role<br/>NOBYPASSRLS, CI-verified"]
    end
    subgraph L4["Layer 4 — Supply chain & CI"]
        SHA["Actions pinned to full commit SHAs"]
        BANDIT["bandit + Trivy (CRITICAL,HIGH)"]
        SECRET["TruffleHog secret scan (base/head)"]
        BP["Branch protection: required checks + CODEOWNERS"]
    end
    L1 --> L2 --> L3 --> L4

Controls matrix

ControlMechanismVerified by
TransportTLS at ingress; ALLOWED_ORIGINS allowlist (no wildcard in prod)deploy checklist
AuthNSHA-256 hashed API keys; generic 401/403 messages (no reason leakage)test_auth_multitenancy.py
AuthZScope RBAC + tenant binding; explicit tenant_id in every SQL predicatetest_required_auth_gateway.py
TenancyFORCE ROW LEVEL SECURITY on pgvector + app-level resolve_tenantlive CI job with least-privilege role (test_pgvector_integration.py)
Least privilegeprovision_db_roles.py: DML-only runtime role, invariant fails the buildtest_db_role_provisioning.py
Encryption at restFernet field-level on content (+ content_plain search projection)test_encryption.py
PIIRegex scrubbing: emails, phones, SSNs, credit cards, sk-*, Aadhaar, PANtest_p0_safety_regressions.py
GDPRPOST /api/security/gdpr-delete — per-tenant hard delete, audited countcontract tests
Abuse controlRedis distributed sliding-window limiter; 429s metricizedtest_rate_limit.py (14)
Secrets hygieneTruffleHog on push/PR (base..head), SHA-pinned actionsCI secret-scan job
Vulnerabilitiesbandit (Python), Trivy CRITICAL+HIGH (images), mypy strict typingCI matrix

Known limitations (tracked in SECURITY.md)

  1. RLS admin path (fixed in v1.3.0) — the admin connection now bypasses RLS via current_user = '<admin_role>' inside the policy, not a settable GUC sentinel. The app layer remains authoritative for tenant binding (resolve_tenant requires an explicit tenant for admin principals). Raising app.current_tenant or any other app.* GUC can no longer bypass RLS.
  2. Readable derivatives — embeddings and tsvector are derived from plaintext at query time; field encryption covers content. Treat backup/volume encryption as mandatory.
  3. Retention windows are operator policy — no background hard-delete job ships; GDPR delete is per-tenant explicit.

12. Observability

Health & probes

ProbeTargetMeaning
GET /livenessengineProcess alive — DB-independent, stays OK during an outage (K8s livenessProbe)
GET /readinessengineDB + auth usable → 503 when pgvector is down (K8s readinessProbe, compose healthcheck)
GET /healthengineTelemetry: backend, HNSW, RLS mode, memory count, provider
GET /metricsenginePrometheus text exposition (below)
GET /api/healthgatewayGateway liveness
GET /api/readygateway503 until engine + auth healthy

Prometheus metrics

MetricTypeLabels
synapse_requests_totalcounterpath, status
synapse_request_latency_seconds (+ _sum, _count)summarypath, quantile (0.5 / 0.95, last-500 samples)
synapse_auth_failures_total / synapse_rate_limit_rejections_totalcounter—
synapse_ingest_total / synapse_retrieval_totalcounteroutcome
synapse_retrieval_candidates / synapse_context_tokens_packedgauge—
synapse_memories_totalgaugebackend
synapse_db_pool_in_use / synapse_db_pool_sizegauge—
synapse_rate_limit_backendgaugebackend="redis"|"in-process"
synapse_upgauge— (constant 1)

No hardcoded latency figures exist in the codebase — read p50/p95 off your own deployment's /metrics before setting SLOs (see docs/performance-baseline.md).

Tracing

Pass X-Request-ID on any request; it is echoed in the response envelope and threaded through engine logs, audit entries, and the gateway — one id correlates the whole path.


13. Testing & Quality Gates

CI matrix (.github/workflows/ci.yml, all actions SHA-pinned)

JobWhat it proves
python-lint-and-type (3.10 × 3.11 × 3.12)flake8 clean, mypy strict, bandit clean, clean module imports
python-tests (3.10 × 3.11 × 3.12)full pytest suite (offline: no network, no external DB)
frontend-build (Node 20.x × 22.x)tsc --noEmit lint + production Vite bundle
container-buildmonolithic image builds (validation)
python-pgvector-integration-tests (PG16 service)live RLS/tenancy proof: provision roles → migrate as admin → grant DML → verify invariant → run pgvector suite
split-image-buildengine + gateway images, compose config valid, Trivy CRITICAL+HIGH on both
helm-validatehelm lint, template render, YAML parse + offline contract tests
secret-scanTruffleHog across github.event.before..github.event.after (push) / base..head (PR)

Local gates (mirror CI exactly)

pip install -r requirements-dev.txt && pip install -e "sdk/python[all,dev]"

PYTHONPATH=sdk/python pytest sdk/python/tests -v      # unit + integration tests; gated tests are reported as skipped
flake8 sdk/python/synapse_memory scripts --config=setup.cfg
mypy sdk/python/synapse_memory --config-file=setup.cfg
bandit -r sdk/python/synapse_memory scripts -s B101,B104,B105,B110,B310,B311,B608
npm ci && npm run lint && npm run build

Test suite map

The suite includes unit, contract, security, resilience and PostgreSQL integration tests. Database- and provider-gated cases must be explicitly enabled in a disposable test environment; passing the default offline suite does not prove every production configuration.

SuiteTestsProves
test_load_resilience.py17parallel writers/readers lose nothing; DB outage fail-fast + recovery; slow provider degradation; crash-restart durability; 1000-row corpus
test_rate_limit.py14limiter behavior incl. window edges
test_db_role_provisioning.py20role invariants, idempotency, --verify-only
test_helm_chart.py18offline Helm rendering contracts (env ordering, split services)
test_p1_contract_regressions.py9API envelope, metrics emission, error taxonomy
test_p0_safety_regressions.py4P0 regressions incl. PII scrubbing, fail-closed paths
test_pgvector.py (offline) / test_pgvector_integration.py (live CI job)3 + 16RLS isolation with the real runtime role (not just owner)
test_encryption.py, test_auth_multitenancy.py, test_migrations.py, and the rest63engine-by-engine contracts (see §4)

14. Performance Baseline

Measured methodology and the 5-step SLO process: docs/performance-baseline.md.

LayerBaselineHow it's measured
Retrieval latencyread live p50/p95 per endpoint from synapse_request_latency_seconds{path,quantile} (last-500 window)your own /metrics
PackingDP bounded by O(n · budget); greedy above n·budget > 2Mtest_knapsack.py
Dense indexHNSW (pgvector) — sub-linear scan, index-assistedpgvector CI job
Corpus qualityretrieval-eval corpus, measured-only (no projections)test_retrieval_eval.py
Throughput headroombench suite runs offline with projections labeled; treat as upper boundsbenchmark/bench_suite.py
SLO setting5 steps: collect /metrics → set p95 target per route → record in baseline doc → alert on synapse_request_latency_seconds regressions → re-baseline each releaseprocess, not a number

Policy: no fabricated numbers. The repo deliberately ships zero hardcoded latency claims — every figure must come from a real deployment's telemetry.


15. Operations

On-call guide: docs/ops-runbook.md · Backups: docs/backup-recovery.md

Incident triage flow

flowchart TD
    START["Alert / report"] --> Q1{"gateway /api/ready = 503?"}
    Q1 -->|yes| Q2{"engine /readiness = 503?<br/>/liveness OK?"}
    Q2 -->|yes| DBACT["pgvector down / DSN / pool exhausted<br/>check /health + synapse_db_pool_in_use<br/>failover DB, restart engine"]
    Q2 -->|no| ENG["engine down entirely<br/>check crash-loop logs<br/>(missing schema? env ordering?)"]
    Q1 -->|no| Q3{"429 spike?"}
    Q3 -->|yes| RATE["per-key burst<br/>check synapse_rate_limit_rejections_total<br/>verify Redis backend active, raise limit or re-key"]
    Q3 -->|no| Q4{"403 / cross-tenant concern?"}
    Q4 -->|yes| SEC["rotate keys, audit GET /api/auth/audit<br/>verify resolve_tenant rejects (403)<br/>treat runtime DSN as sensitive"]
    Q4 -->|no| APP["app-level error<br/>trace with X-Request-ID"]

Quick reference

SymptomLikely causeAction
Engine crash-loop with SYNAPSE_APPLY_DB_SCHEMA=falseschema never migratedrun provision + migration as synapse_admin, --verify-only, restart — never flip SYNAPSE_ALLOW_DB_FALLBACK=true in prod
/readiness 503, /liveness OKDB issuetriage order: /health → /metrics pool gauges → failover
404 {simulated: true} on demo routesdemo routes gated offexpected in prod (ENABLE_DEMO_ROUTES=false)
Literal $(DB_PASSWORD) in DSN after Helmenv ordering editedDB_PASSWORD must precede DATABASE_URL in deployment.yaml
429 on one tenantkey-level burstconfirm synapse_rate_limit_backend{backend="redis"} for multi-replica

Scaling

  • Engine and gateway scale independently (separate Deployments; HPA 3–15).
  • Multi-replica rate limiting requires REDIS_URL; without it the effective limit is RATE_LIMIT_PER_MIN × replicas.
  • Bulk ingest ≤ 100 items / 500KB per call; list endpoints paginate (limit ≤ 200); TOKEN_BUDGET_MAX hard cap 8000.
  • Backup/restore: scripts/backup_restore_drill.py (drill-tested, CI-covered).

16. Documentation Index

DocumentContents
docs/quickstart.md5-minute install → create → retrieve → error handling
docs/api-reference.mdevery route, request/response schema, auth requirement, error codes
docs/security-review.mdOWASP API Top 10 (2023) assessment, API1–API10, controls evidence
docs/ops-runbook.mdon-call: health model, deploy checklist, incident playbooks, scaling
docs/backup-recovery.mdbackup strategy + scripts/backup_restore_drill.py drill
docs/performance-baseline.mdmeasured baseline + 5-step SLO process
docs/production-hardening-baseline.mdHistorical hardening checklist, known gaps and current verification status
docs/branch-protection.mdGitHub rule settings: required checks, CODEOWNERS, stale-dismiss
docs/publishing.mdPyPI release pipeline (synapse-memory-engine), trusted publishing, fresh-install guarantee
SECURITY.mdthreat model, known limitations, vulnerability disclosure
CHANGELOG.mdrelease history + compatibility matrix
CONTRIBUTING.md · CODE_OF_CONDUCT.mdPR workflow, code of conduct
CODEOWNERSreview ownership for all paths (@721189)

17. Repository Structure

Synapse-Memory/
├── sdk/python/                     # Python package (published as synapse-memory-engine)
│   ├── synapse_memory/
│   │   ├── core/                   # engines: memory_manager, hybrid_search, knapsack_packer,
│   │   │                           # decay_engine, deduplicator, auth, encryption, embedder,
│   │   │                           # sqlite_db, pgvector_db, rate_limiter, observability,
│   │   │                           # pruner, migrations
│   │   ├── api/fastapi_server.py   # HTTP engine :8008 (26 routes, envelope, metrics)
│   │   ├── client.py               # SynapseClient (typed, retries, envelope-aware)
│   │   ├── integrations/           # langchain.py, llamaindex.py
│   │   └── cli/synapse_cli.py      # synapse / synapse-memory entrypoints
│   ├── benchmark/                  # bench_suite.py (offline, projections labeled)
│   └── tests/                      # 23 suites: P0/P1 regressions, load, pgvector, helm, …
├── src/                            # React dashboard (13 tabs: retrieval, decay, knapsack,
│                                   # security, poisoning lab, RLAIFF, graphs, …)
├── server.ts                       # Node gateway :3000 (proxy, CORS, readiness)
├── deploy/
│   ├── docker-compose.yml          # 4 services, health-gated dependencies
│   ├── .env.example                # single source of truth for configuration
│   └── helm-chart/                 # engine+gateway Deployments, HPA, Ingress, NOTES.txt
├── scripts/
│   ├── provision_db_roles.py       # least-privilege roles, invariant verification
│   └── backup_restore_drill.py     # backup/restore drill
├── docs/                           # see §16 Documentation Index
├── examples/knowledge_assistant_api/  # end-to-end example server
├── .github/workflows/ci.yml        # 8-job matrix, SHA-pinned actions
├── Dockerfile.engine / Dockerfile.gateway   # split production images
├── SECURITY.md · CODEOWNERS · CHANGELOG.md

18. Release History

VersionDateHighlights
1.5.12026-12-01Published to PyPI under Apache 2.0; adds the MCP distribution launcher alias and publishes io.github.721189/synapse-memory to the official MCP Registry through GitHub Actions OIDC.
1.5.0—MCP stdio server backed by the authenticated Synapse API; tenant-bound memory tools and metadata-only agent-run inspection.
1.4.02026-10-30Agent run guard and persistent tenant-scoped run traces; PyPI artifact published with provenance and retains its original proprietary terms.
1.3.12026-10-27Correctness and release hardening: pgvector halfvec HNSW compatibility for shipped 3,072-dimensional embeddings; guard against implicit embedding-width changes; safer SDK retry semantics; Compose failure diagnostics; aligned version metadata; least-privilege migration-role validation; tenant aliases; production gateway data hygiene. Python SDK published to PyPI.
1.2.02026-10-15Production-hardening release: NULL-safe RRF, combined-protection encryption (content + content_plain), S = R × D decay composition, fail-closed gateway, thread-safe pooling, Helm split workloads (18 contract tests), load/resilience suite (17 tests), /metrics, distributed rate limiting, least-privilege roles, SynapseClient, retrieval-eval corpus
1.2.0 (hardening)2026-10-16/17P0–P2 roadmap closed: RLS live proof with runtime role, SHA-pinned CI, TruffleHog base/head fix, query_candidates tenant-scoped PG path, final docs batch (api-reference, security-review, branch-protection, performance-baseline, CODEOWNERS)
0.1.0—Pre-hardening prototype — do not use in production

Open production-readiness work: validate a fresh PostgreSQL/pgvector Compose deployment; measure p95/p99 SLOs on intended hardware and workloads; complete independent security review; and validate real customer usage. See the current hardening status and SECURITY.md.


19. Contributing

  1. Read CONTRIBUTING.md and CODE_OF_CONDUCT.md.
  2. Branch from main; all local gates must pass before pushing (§13 commands).
  3. CI must be green on your PR — lint/type, tests (3 Python versions), frontend build, container scans, Helm validation, secret scan.
  4. CODEOWNERS review required; branch protection spec in docs/branch-protection.md.
  5. Keep docs in sync: user-visible changes update CHANGELOG.md + relevant docs/* page.
flowchart LR
    F["Fork / branch"] --> L["Local gates<br/>flake8 · mypy · bandit · pytest · npm build"]
    L --> P["Open PR"]
    P --> CI["CI matrix (8 jobs, SHA-pinned)"]
    CI -->|red| F
    CI -->|green| R["CODEOWNERS review<br/>+ required checks"]
    R --> M["Merge to main<br/>→ release gate green"]

20. License

The Synapse Memory source code in this repository is licensed under the Apache License, Version 2.0.

This grant covers the original project code and documentation in this repository unless a file or directory carries a separate license notice. Third-party dependencies, model weights, and other externally supplied assets remain under their own licenses; they are not relicensed by this project license. See the licensing policy for the open-core boundary and dependency-audit procedure.

The Apache License does not grant rights to use the Synapse name, logos, or other project trademarks. See TRADEMARKS.md.


Synapse Memory — memory infrastructure for persistent, tenant-aware AI applications.

Documentation · API Reference · Security · Runbook · Changelog · Issues

PYPI
synapse-memory-engine
Install Command
pip install synapse-memory-engine
Runtime: uvx