MESA Core · v0.9.3

HTTP API ve Python SDK

v0.9.3 kaynak: docs/api-reference.md

Bu rehberin Türkçe ve İngilizce sürümleri aynı konuyu açıklar. Bu sayfayla ilgili kaynak bölümleri en altta yer alır.

Kimliği doğrulayın ve erişim kapsamını belirleyin#

Her uç noktanın istek gövdesi, alanları ve yanıt kodları için HTTP uç nokta referansına bakın.

Sürümlü hafıza, sağlık ve ölçüm isteklerinde X-API-Key gerekir. Dışarıya açık /health/init, OpenAPI, Swagger ve ReDoc için ağ erişim kurallarını kurulumda ayrıca belirleyin. Veri kümeleriyle sınırlı bir oturum açmadan önce katalog kaynaklarını yetkili erişim kimliğiyle oluşturun. SDK örneği işlemin son durumunu açıkça kontrol eder.

Kullanılabilen API işlemleri#

MetotYolAmaç
GET/v4/capabilityKullanılabilir özellikler ve yeniden oluşturma sınırları
POST / GET/v4/catalog/workspacesÇalışma alanı kataloğu
POST / GET/v4/catalog/datasetsVeri kümesi kataloğu
POST / GET/v4/catalog/documentsBelge kataloğu
POST / GET/v4/catalog/revisionsDeğiştirilemeyen belge sürümleri
POST/v4/catalog/source-chunksTam kaynak parçaları
POST/v4/sessions/startOturumun erişebileceği veri kümelerini belirleme
POST/v4/memory/insertDeğişiklik isteğini kalıcı kayda alma (202)
POST/v4/documentsTam belgeyi kayıpsız parçalama, tekrar tespiti ve sürüm takibiyle alma (202)
POST/v4/memory/searchErişim izinlerine göre hibrit arama
GET/v4/mutations/{mutation_id}İşleme durumunu izleme
POST/v4/mutations/{mutation_id}/replayYetkili yeniden yürütme
POST/v4/mutations/{mutation_id}/rollbackKaynağın sahiplik bağını geri alma
GET/v4/sessions/{session_id}/contextSınırlı kanıt bağlamı
POST/v4/sessions/{session_id}/endKalıcı oturum sonlandırma

Yanıtları nasıl yorumlamalı?#

HTTP 202 yalnızca isteğin kabul edildiğini bildirir. Başarılı bir yazma COMMITTED durumuna ulaşmalıdır. Arama yanıtı; rrf_score, legal_factor, raw_score, final_score ve katkı veren kanalları içerir. Modeller kapalıyken combined çalışma belgeleri kabul eder ve BM25 araması sağlar; VECTOR adımları SKIPPED olur. 503 canonical_processing_unavailable, combined tüketicinin kullanılamadığını belirtir. Yönetim amaçlı yeniden oluşturma ayrı bir işlemdir ve varsayılan olarak kapalıdır. Tam istek şemaları, diğer yönetim işlemleri ve yetkilendirme ayrıntıları aşağıdaki özgün kaynakta bulunur.

Tam belge alımı#

POST /v4/documents; session_id, dataset_id, document_id, title, source_ref, content ve isteğe bağlı metadata alır. Yanıt revision_id, revision_number, chunk_count, mutation_ids ve duplicate içerir. Her mutasyon için COMMITTED bekleyin. Aynı ACTIVE içerik kimliklerini yeniden kullanır; değişen içerik yeni sürüm oluşturur. Sınır 5.000.000 UTF-8 bayttır; boş metin 422 döndürür ve silinmiş belge kimliği yeniden kullanılamaz. Mesa().add() bu uç noktayı kullanır.

Kendi sayfasına taşınan bölümler
Kaynak belgedeki ilgili bölümler

Bu bölüm, kaynak belgenin bu sayfayla ilgili kısımlarını değiştirmeden gösterir. Kaynak içindeki bir bölüme giden bağlantıyı açtığınızda metin otomatik olarak görünür.

MESA v4 tenant/dataset yetkili versioned API sunar. Paket 0.9.3; yayın sahibinin adımıdır ve production sertifikasyonu içermez.

Versioned memory, health ve metrics çağrıları X-API-Key ister. /health/init, OpenAPI, Swagger ve Redoc public yüzeylerdir; ağ/reverse-proxy politikası gerekir. V4 anahtarı

mesa-v4-admin issue-key ile üretilir; yalnız saltlı scrypt özeti saklanır.

OpenAPI sözleşmesinin çalışan kaynağı mesa_api/v4_router.py dosyasıdır.

V4 capability#

GET /v4/capability returns api_version, features, capabilities and

limits. features contains the capability names whose values are true.

The response depends on the configured and operational runtime; a sample

response must not be used as a fixed feature promise.

CapabilityMeaning
canonical_ledger, projection_outbox, idempotent_ingestionDurable canonical work and projection contracts
vector_retrievalOperational embedding generation, not merely configured identity
lexical_retrieval, assertion_relational_laneSQLite lexical/assertion retrieval; not graph traversal
graph_projectionGraph projection availability
graph_neighbor_retrievalOperational neighbor retrieval implementation
validity_interval_filteringValidity filtering, not bitemporal semantics
durable_rebuildEnabled by MESA_V4_REBUILD_ENABLED; still offline and full-root
associative_ppr, bitemporal_query, human_reviewNot advertised as implemented Core capabilities

Rebuild limits are rebuild_kind=projection, rebuild_scope=storage_root, and

requires_offline_runner=true. A projection-only graph adapter does not supply

neighbor retrieval. Custom embedding providers are non-operational until a

successful embedding call. Configured backend failure is surfaced explicitly;

see retrieval behavior and troubleshooting.

V4 administrative rebuild operations#

Bu yüzey yalnız control-plane ADMIN principal içindir ve fiziksel path veya

canonical içerik kabul etmez:

MethodPathBaşarıİşlev
POST/v4/operations/rebuild202Zorunlu Idempotency-Key ile storage-root operation submit eder
GET/v4/operations/{operation_id}200Content-free state/progress döndürür
POST/v4/operations/{operation_id}/cancel200Yalnız PENDING/RETRYABLE_FAILED operation'ı iptal eder
POST/v4/operations/{operation_id}/retry202Güvenli RETRYABLE_FAILED checkpoint'ini tekrar pending yapar
POST/v4/rebuild202Deprecated storage-root alias

Flag kapalı submit/retry 501, unsupported scoped alias 409, invalid state

409 döndürür. Yetkisiz status/cancel/retry operation varlığını sızdırmamak

için 404 olur. State akışı

PENDING → CLAIMED → RUNNING → VERIFYING → READY_TO_CUTOVER → COMPLETED;

yan durumlar RETRYABLE_FAILED, FINAL_FAILED ve CANCELLED'dır. Aktif veya

retryable operation sırasında mutation admission'ı 503 maintenance_pending

olur. Offline işletim prosedürü

`v4-rebuild-runbook.md` içindedir.

V4 catalog#

MethodPathGerekli yetkiİşlev
POST/v4/catalog/workspacesTenant OWNERTenant/workspace oluşturur
GET/v4/catalog/workspacesGörünür kapsamda READERWorkspace listeler
POST/v4/catalog/datasetsDataset/workspace OWNERDataset oluşturur
GET/v4/catalog/datasetsGörünür kapsamda READERDataset listeler
POST/v4/catalog/documentsDataset WRITERDocument oluşturur
GET/v4/catalog/documentsDataset READERDocument listeler
POST/v4/catalog/revisionsDataset WRITERImmutable revision oluşturur
GET/v4/catalog/revisionsDataset READERRevision listeler
POST/v4/catalog/source-chunksDataset WRITERExact source chunk oluşturur
DELETE/v4/catalog/documents/{document_id}Dataset OWNER + PURGEKaynak sahipli purge başlatır

Document purge erases its source and extracted text while retaining identifiers and hashes; shared assertion/entity text remains while another document still owns it.

Catalog IDs are tenant-scoped public IDs; physical storage keys are not public

aliases. Revision/chunk identity, finalization and the distinction between

declared_content_hash, manifest_hash and chunk content_hash are defined in

concepts and ingestion.

V4 session ve memory#

MethodPathİşlev
POST/v4/sessions/startSunucu üretimli, dataset kapsamı değişmez session başlatır
POST/v4/memory/insertExact source’u kabul edip mutation ve pipeline run oluşturur
POST/v4/memory/searchYetkili datasetlerde vector/BM25/assertion/graph RRF araması yapar
GET/v4/mutations/{mutation_id}State, pipeline, artifact ve projection durumunu verir
POST/v4/mutations/{mutation_id}/replayYetkili DLQ/retry işini yeniden kuyruğa alır
POST/v4/mutations/{mutation_id}/rollbackKaynak sahipli rollback başlatır
GET/v4/sessions/{session_id}/contextSession context ve mutation provenance’ını verir
POST/v4/sessions/{session_id}/endDurable finalization ister ve session’ı kapatır

Insert derives tenant/workspace/agent from the authorized session and returns

202 with mutation_id, candidate_id, pipeline_run_id and raw_log_id.

This is admission; poll status and require COMMITTED before assuming success.

wait_until_committed() also returns failed terminal states.

For multiple chunks use distinct IDs/ordinals, finalize_revision=false until

the last insert, then true. Retry the exact payload with the same body

idempotency_key. Revision lifecycle, rejection/replay and rollback semantics

are defined in concepts and ingestion.

The HTTP insert contract accepts optional typed legal_identity: law_id and

article_id are required within that object; statute_code, version_id,

paragraph_id and clause_id are optional. Identity must resolve consistently

through the bounded legal aliases. Caller metadata cannot supply trusted

_mesa_* fields. The producer remains responsible for source truth.

Search responses include degraded_sources: vector when embedding is off or any in-scope committed record has an incomplete VECTOR lane, and graph under the same rule for GRAPH or MESA_GRAPH_ENABLED=false; otherwise [].

Search and context both accept jurisdiction, valid_at, valid_from and

valid_to. Context uses query parameters and defaults to token_budget=2048,

retrieval_mode=single. Opt-in adaptive permits at most one planner call and

two additional scoped searches. Scores, graph provenance, proof packing and

offline token counting are defined in retrieval and graph.

Raw /v4/memory/search remains the single-query primitive.

V4 Python SDK#

Bu örnek, model-enabled V4 sunucu, provision edilmiş credential, mevcut

tenant-a/workspace-a/dataset-a kataloğu ve agent-a session izni varsayar.

Bunları da kuran örnek için Getting started kullanılır.

python
from mesa_client import MesaV4Client

with MesaV4Client("http://127.0.0.1:8000", api_key=credential) as client:
    session = client.start_session(
        tenant_id="tenant-a",
        workspace_id="workspace-a",
        dataset_ids=["dataset-a"],
        agent_id="agent-a",
    )
    accepted = client.insert(
        session_id=session["session_id"],
        dataset_id="dataset-a",
        document_id="doc-a",
        revision_id="rev-1",
        chunk_id="chunk-1",
        title="Neutral source example",
        source_ref="demo://source-a",
        content="Exact source text",
    )
    terminal = client.wait_until_committed(accepted["mutation_id"])
    if terminal["state"] != "COMMITTED":
        raise RuntimeError(terminal["state"])
    result = client.search(session_id=session["session_id"], query="Exact source")
    for hit in result["results"]:
        print(hit["assertion_id"])
        for source in hit.get("provenance", []):
            print(source["source_ref"], source["dataset_id"], source["chunk_id"])
    context = client.get_context(session_id=session["session_id"], query="Exact source")
    print(context["context"])
    client.end_session(session_id=session["session_id"])

accepted is durable admission, not finished retrieval. client.status(mutation_id)

exposes state, failure_class, rejection_reason, pipeline_run, artifacts

and projections. Wait for COMMITTED; REJECTED, DEAD_LETTER, BLOCKED and

ROLLED_BACK are terminal outcomes too. A wait timeout raises MesaNetworkError

and leaves the mutation running. Recheck status; for an uncertain insert retry

the same payload with an explicit, unchanged idempotency_key.

results=[] on a successful search means no matching visible evidence. Provider,

storage and authorization failures raise errors instead. Each hit's

assertion_id identifies a canonical claim; provenance links it to the source

and dataset/chunk. A score ranks evidence; it is not a truth probability.

Context returns packed text in context and structured evidence in

canonical_memories; mutations holds bounded receipts (IDs and states) without raw evidence spans. Finish retrieval before end_session; closing the HTTP

client alone does not end the server session.

For async code use async with AsyncMesaV4Client(...) as client and await each

of these methods, including polling and end_session. Do not run the blocking

MesaV4Client inside an event loop. Async clients also support await client.aclose();

sync clients support client.close().

Çok chunk'lı revision için ilk çağrılarda finalize_revision=False, son

çağrıda varsayılan True kullanılır. search ve get_context metotları

valid_at, valid_from ve valid_to parametrelerinin üçünü de destekler.

MesaV4Client ve AsyncMesaV4Client; capability, catalog, session, insert,

search, status, wait, replay, rollback, purge, context ve end işlemlerinin

yanında submit_rebuild, operation_status, cancel_operation ve

retry_operation control-plane metotlarını sunar. V3 istemcileri MesaClient

ve AsyncMesaClient olarak korunur. Dataset-bound MCP yüzeyi mutating global

rebuild aracı sunmaz.

V4 authorization#

Route katmanı şu bağlamı sunucu tarafında çözer:

text
principal → tenant → workspace → dataset → agent → session

OWNER, WRITER ve READER rolleri aşağı doğru miras kalır. Purge ve

rollback için ayrıca dataset PURGE veya ROLLBACK izni gerekir. Agent bir

persona/hesaplama bağlamıdır; tek başına güvenlik sınırı değildir.

Rollback ve replay tarihsel yönetim işlemleridir; originating session kapalı

olabilir. Bununla birlikte principal/session ownership, mutation ile session'ın

tenant/workspace/dataset/agent scope eşleşmesi, dataset rolü ve açık

ROLLBACK izni her çağrıda doğrulanır.

Provision keys, roles and explicit dataset permissions using the

operations runbook; the

CLI reference identifies admin entry points. RBAC uses its

own schema version in the policy database, independently of Alembic migrations

for canonical storage. Lost grants from an old database cannot be inferred or

recreated automatically.

Internal DAO ownership, projection and Graph V2 structure belong in the

architecture; they are not separate public HTTP methods.

Health ve metrics#

  • /health: API anahtarıyla status, maintenance, rebuild_state özeti
  • /health/init: public readiness; hazırsa 200 {"status":"ready"}, değilse 503
  • /metrics: API anahtarıyla Prometheus sayaçları ve gauge'ları

/health degraded veya maintenance durumunda da HTTP 200 dönebilir; yalnız

HTTP kodunu başarı saymayın, status alanını kontrol edin. Ayrıntılı kuyruk,

projection ve rebuild sayaçları /metrics üzerinden okunur.

V4 metrikleri projection backlog/DLQ/stuck lease, cleanup backlog/BLOCKED,

ownerless registry, shared artifact ve rebuild state/duration/progress,

parity-missing, staging-byte ve rollback sayılarını kapsar. Alert kuralları

docs/prometheus_alerts.yml içindedir.

İstek/SDK ayrıntıları#

V4 HTTP insert ve sync/async SDK insert için title zorunludur. title 1..512,

content 1..32768 karakter, source_ref 1..2048, evidence_span en çok 4096,

idempotency_key en çok 128 karakterdir. Dataset session üyeliğinde olmalıdır.

HTTP ve sync/async SDK insert, opsiyonel legal_identity parametresini destekler.

Public/source ID validator farkları için çalışan OpenAPI kullanılır.

Search request session_id, query gerektirir; query 1..4096 karakter,

limit default 10 ve 1..50, dataset_ids verilirse 1..64 ve session altkümesi,

graph_mode enabled/disabled'dır. ISO timestamp string'leri timezone offset

içermelidir. valid_from > valid_to reddedilir. Response session_id,

dataset_ids, results, optional scope_audit, graph_ablation, vector_lane

taşır. Sonuç provenance'ın varlığı source truth garantisi değildir.

SDK sync/async client timeout default 10s ve max_retries 3; yalnız güvenli

network retry boundary geçerlidir. API HTTP hata yanıtları MesaAPIError,

network MesaNetworkError, SDK schema MesaValidationError olur. Status

400/401/403/404/409/413/422/429/503 endpoint'e göre değişir; OpenAPI ve contract

testleri kaynak otoritesidir. Queue saturation/rebuild maintenance için

Retry-After dikkate alınır. Dakikalık (60/minute) ve günlük (10000) istek limitleri

bu sürümde uygulanmamaktadır (per-minute and daily limits are not enforced in this version).

Whole documents: POST /v4/documents#

Send session_id, dataset_id, document_id, title, source_ref, content

and optional metadata. The session requires WRITE access to the dataset and

the runtime must own the combined consumer, just as for /v4/memory/insert.

The server splits content into consecutive slices of at most 512 cl100k tokens,

preferring blank lines, then sentence ends, then hard cuts. Joining the slices

reproduces the input exactly, including whitespace.

HTTP 202 returns document_id, revision_id, revision_number, chunk_count,

mutation_ids and duplicate. It means admission; poll each mutation until

COMMITTED before relying on the new revision in search. A changed document

gets the next revision number and supersedes the active revision when all its

chunks commit. Repeating the same document and content returns its existing IDs

with duplicate: true for an ACTIVE revision, using its stored chunk count and

mutation IDs without rechunking. Retrying an interrupted PENDING upload resumes

its missing chunks. Other matching revisions return 409 `content equals revision

<n> (<status>); restoring an earlier revision is not supported in v0.9`.

Revision IDs are rev- plus the first 32 hex characters of

sha256(document_id + "\n" + sha256(content)), with the inner hash represented

as lowercase hex and strings encoded as UTF-8. Chunk IDs append -c and a

zero-based five-digit ordinal. Per-chunk idempotency keys are these chunk IDs.

Errors: 409 document is purged; 413 for content over 5,000,000 UTF-8 bytes;

422 for empty or whitespace-only content. Secrets and metadata use the same

validation and errors as /v4/memory/insert. Queue and maintenance failures

use the existing admission errors below.

Actionable errors#

Catch MesaAPIError to inspect status_code, error and detail. HTTP bodies

also include retryable; the SDK does not automatically retry HTTP failures.

Rejected request values and internal route paths are omitted from validation

errors. For example, a non-string search query returns HTTP 422:

json
{"error":"VALIDATION_ERROR","detail":"body.query: Input should be a valid string","status_code":422,"retryable":false}
ResponseNext step
401 UNAUTHORIZEDSupply the issued MESA key, not the provider key
403 ACCESS_DENIEDCheck tenant/dataset roles, agent grant and session scope
404 NOT_FOUNDCheck the ID and credential scope; hidden objects may also return 404
409 SESSION_INACTIVEStart an authorized active session before new writes
409 IDEMPOTENCY_CONFLICTReuse the original payload with that key, or use a new key for new content
409, detail document is purgedRe-using a purged document ID is not supported; use a new document ID
422 VALIDATION_ERRORCorrect the named field/format; timestamps need a timezone
503 BACKEND_UNAVAILABLE, detail canonical_processing_unavailableRun one combined owner; non-combined profiles cannot ingest V4
503, detail vector_backend_unavailable / graph_backend_unavailableCheck provider credentials, embedding identity and backend readiness; an empty result is not a substitute
503, detail queue_over_capacity / maintenance_pendingRespect Retry-After when present and wait for capacity/maintenance

Failed background processing is reported by mutation status even when the insert

returned 202. Inspect its failure/projection fields; an admission response or an

empty early search does not establish successful processing. Startup

configuration errors appear in the server terminal before readiness; see

configuration.

List catalog çağrıları burada açıkça belgelenmiş pagination garantisi sunmaz;

response/schema'yı inceleyin. İlk catalog/ACL ve credential ön koşulları dahil

çalıştırılabilir örnek Getting started içindedir.

Canonical V4 insertion requires the combined processing consumer. With models

off, it stores records with a SKIPPED VECTOR lane and finds them through BM25.

Enabling embedding later backfills skipped lanes without hiding committed records.

The OpenAPI snapshot is a generated reference.

Use the running app's /openapi.json and route/schema source for the exact

checkout; do not infer snapshot freshness from this page. Generating a schema

without server startup does not exercise authentication or runtime behavior.