Skip to content

About

Fusion shared core library - unified FusionMLXClient for Python projects

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

doc_id fusion-core/readme
product fusion-core
class platform
entry developer
doc_type readme
title
zh en
Fusion-Core 公共技术底座
Fusion-Core shared technical foundation
audience engineer
status draft
version 0.14.0
updated 2026-11-07
owner @dahai
source_of_truth
README.md
pyproject.toml

fusion-core

Shared technical foundation for the Fusion ecosystem. Pure-tech, zero business logic.

中文文档

fusion-core is the common technical base shared by the 20+ Python domain projects in the Fusion ecosystem ("一核九端"). It eliminates 7+ duplicate LLM clients and 10+ copies of _parse_json by providing one well-tested implementation of each primitive: an LLM client, JSON parsing, config loading, logging, an httpx connection pool with retry, a FastAPI factory, prompt-template management, and a zero-trust guard client.

It depends on nothing Fusion-specific. import fusion_core triggers no I/O (no env read, no file read, no network connection) — safe to import anywhere.

Install

pip install fusion-core               # from PyPI (published automatically on stable tags, issue #52)
pip install -e fusion-core            # from the monorepo tree — core (httpx only; zero business deps, no pydantic)
pip install -e "fusion-core[test]"    # + test stack (pytest, ruff, fastapi, jsonschema)
pip install -e "fusion-core[fastapi]" # + fastapi, uvicorn, pydantic
pip install -e "fusion-core[schema]"  # + jsonschema (for dsl_schema validation)
pip install -e "fusion-core[proc]"    # + setproctitle (for set_process_title)

Requirements: Python >=3.12.

17 modules at a glance

Module Key symbols Purpose
mlx_client FusionMLXClient, create_async_client(*, backend=), LLMResponse, EmbeddingResponse, ServerStats, StreamError Unified MLX inference client (chat / embedding / stream). Default base_url localhost:11434 (resolved at runtime from FUSION_MLX_URL; point it at fusion-gateway for multi-node). Retry delegated to http_client. chat(total_deadline=) is an explicit named param (R5) for the end-to-end budget; **kwargs allowlist-passes (top_p/seed etc.); stream_chat raises StreamError(delivered=, resume_offset=) for all stream-failure paths (mid-stream severed OR retriable-exhausted-no-output) so callers have ONE stream-failure type (H4/R4); non-retriable 4xx still raise the original HTTPStatusError; create_async_client(model=...) records a default model; health() reuses a probe_client with 1s throttle (no main-connection leak); get_server_stats() returns a ServerStats dataclass. Stream chunk parsing tolerates gateway terminator chunks: {"choices": [null]} or delta: null are skipped, not AttributeError (issue #44); extra_body= merges engine-specific payload fields verbatim (shallow merge, explicit params win on collision — issue #49); code_mode=True passes the fusion-mlx M10 code_mode field through (tools rendered as Python stubs server-side; unset = identical request — issue #54); chat_json() = response-level retry for JSON extraction (retries only unusable replies — empty/unparseable; budget via attempts= or FUSION_CORE_CHAT_JSON_RETRIES, exhaustion raises ParseError)
ops OpsEmitter, EmitterStats, OpsEmitterDependencyError Async batched ops-event emitter to PG public.ops_events (schema v1 per fusion-ops migrations, issue #58; CHECK-validated source, INTEGER status coercion, drop_counters backpressure reporting) — emit() never blocks: full queue = drop + throttled counter, flush failure = batch drop + jittered reconnect backoff; batch size / flush interval / queue cap configurable; asyncpg lazy-imported via the [ops] extra (import stays I/O-free); connect= test seam
desensitize desensitize, pii_classes, DesensitizeResult PII/secret masking toolkit v1 (issue #56) — email/phone/idcard/secret (jwt, sk-, hex/b64 >=32)/credit-card (Luhn-validated)/IP masks; credential-URL stripping; username/tenant -> 8-char sha256 hash tokens; hard-deny list (raw password/session-token/captcha values) fails the whole sample (masked="")
parse parse_llm_json (raises ParseError, no fallback), parse_llm_json_safe (explicit default required, must be dict/list), parse_llm_json_lenient (raw_decode extracts first object, scan cap 200k), strip_code_fence Parse JSON from LLM output. Failures are visible, never silent
config load_settings (mtime-invalidated cache), resolve_api_key, load_api_key, get_env, default_mlx_base_url, clear_cache, client_key, admin_key, gateway_admin_key, profile, gateway_base_url, service_port, service_data_dir Lazy config load + api_key resolution + cache invalidation (settings file mtime change → cache miss). Since v0.7.0 also the single-point resolution layer for architecture/config-conventions.md (issues #31/#32): client_key() resolves FUSION_CLIENT_KEY → FUSION_MLX_API_KEY → MLX_API_KEY (legacy names warn); admin_key() reads FUSION_ADMIN_KEY (no aliases); gateway_admin_key() (issue #35) resolves FUSION_GATEWAY_API_KEY → settings.json shell.gateway_admin_key — the key the gateway actually accepts; profile() reads FUSION_PROFILE (dev = warn-once + "", prod = 3-part RuntimeError); gateway_base_url() defaults http://127.0.0.1:11432; service_port(app, default) / service_data_dir(app, default) read FUSION_<APP>_PORT / _DATA_DIR with the fusion- prefix stripped (issues #34/#36 — "fusion-rag" and "rag" resolve identically) and port-registry hints
logging setup_logging, get_logger Idempotent logging init (every setLevel applies; propagate defaults True so host root still receives logs; package-level NullHandler for library mode). Optional JSON format. extra={} fields rendered by both formatters (JSON: merged top-level; text: key=value suffix — issue #50); root=True attaches to the root logger for legacy-pattern migration (idempotent)
http_client get_async_client (per-loop connection pool, OrderedDict LRU cap 8, evicts only same-loop keys), gateway_circuit_breaker_ok (probes gateway /readyz, H3/E4), with_retry (full jitter; disable= + verify_gateway= to hand retry off to gateway circuit breaker safely; total_deadline= end-to-end budget; exhausted → RetryExhaustedError / RetryTimeoutError), close_all, close_all_sync, set_metrics_callback, get_metrics_snapshot, reset_metrics httpx async client pool + retry. Single source of truth for retry codes/exceptions: RETRY_STATUS / RETRY_EXCEPTIONS
http create_app, install_auth, standard_error_handler FastAPI app factory + pure-ASGI middleware (install_auth re-orders user_middleware so request_id is outermost — 401 carries the same id, H1/E1; SSE not truncated; auth keys encapsulated in the middleware instance, never on app.state; 422 and 500 sanitized equally; whitelist paths rstrip-normalized). create_app(readiness_probe=) mounts /ready (readiness, 200 ready / 503 not_ready, unauth) alongside /health (liveness)
prompt PromptManager Prompt-template management (engine only, no domain content; missing dir raises FileNotFoundError; mtime-gated cache — on-disk edits are picked up at runtime (mtime change invalidates the entry), clear_cache() forces a full refresh (E3))
guard_client FusionGuardClient, GuardVerdict, GuardRule, RedactResult, ChainVerification, AllChainsVerification, GuardError + 8 typed subclasses Pure-Python UDS JSON-RPC 2.0 client for fusion-guard (the zero-trust action-authorization daemon). Newline-framed (0x0A, 1 MiB cap), 2 s default timeout, per-call reconnect-on-drop with one retry. Methods map 1:1 to guard.ping / guard.evaluate / guard.rule.list / guard.redact / guard.reveal / guard.confirm / guard.tcc.status / guard.tcc.events / guard.audit.verify. Block verdicts are results, not errors (E5) — evaluate() returns GuardVerdict(action="block"); RPC error codes map to typed exceptions (GuardUnauthorizedError -32001, GuardRateLimitError -32002, StaleEpochError -32003 carrying caller_epoch/guard_epoch, GuardEngineError -32010). Default socket /tmp/fusion-guard.sock resolved lazily at call time from FUSION_GUARD_SOCK (import = no I/O). Context-manager lifecycle; native fg-pyo3 stays an optional fast path
tenant TenantContext, current, set_context, reset, has_scope, from_mapping, decode_jwt_claims, tenant_context_from_token, TenantMiddleware, install_tenant_middleware, get_tenant_dep L1 multi-tenant fabric. TenantContext (frozen-slots dataclass over contextvars) carries tenant_id/user_id/role/jti/scopes request-scoped; TenantMiddleware is a fail-closed ASGI middleware — exempt paths skip, missing X-Tenant-Id → 401, JWT tid ≠ X-Tenant-Id → 401, missing bearer when require_jwt=True → 401, binds context for the request then reset() in finally (no cross-request leak). jwt_utils does base64url decode + exp check with no PyJWT dependency, no signature verify — real signature verification is injected via the verify_jwt hook (sync or async; an awaitable return is awaited so a blocking verifier does not stall the event loop — issues #23/#24; lives in fusion-identity). authenticated flag (issue #37): True only when a verified JWT produced claims — consumers write if ctx and ctx.authenticated: instead of reconstructing evidence from optional role/jti/scopes (anonymous contexts no longer mistakable for verified). _JsonFormatter auto-injects tenant_id/user_id from current() into log records. Trilingual mirror anchor (Python variant; Rust/Swift variants land in their own repos)
prompt_registry PromptVersionRegistry, PromptVersionRecord, compute_version_id, is_valid_version_id Immutable prompt-template versioning + replay (issue #28). Content-addressed version_id (16-hex sha256 of name+text) — edits create new versions, snapshots are write-once, every read re-verifies sha256 (tamper = SnapshotIntegrityError). render(prompt_version, **vars) re-materializes the exact prompt bytes (same {{var}} semantics as PromptManager); replay(prompt_version, client) re-runs it through an injected FusionMLXClient (point at gateway :11432 for cluster). Storage = plain files: versions/<id>.txt + index.json, atomic writes. No new deps
dsl_schema SOCRATIC_DSL_V3_SCHEMA, validate_dsl, validate_dsl_str Canonical JSON Schema (Draft 2020-12) for the Socratic DSL v3.0 — the shared contract across fusion-k12-teacher (generate), fusion-bench (evaluate), fusion-artifacts-engine (parse), fusion-trainer (sample validation). Enforces meta (id/grade/topic/visual_type/fallback_type), parameters, entities, pipeline with step required fields (step/title/formula/eval/result_unit/visual_state); visual_type enum (8 values: array_grid/tape_diagram/geometry_2d/isometric_3d/track_timeline/bucket_divider/data_chart/flow_card), fallback_type enum (2 values: tape_diagram/flow_card). validate_dsl(dict) -> bool and validate_dsl_str(str) -> tuple[bool, str] (parse + validate, returns error path). jsonschema is a lazy import inside validators — import fusion_core stays I/O-free; install [schema] extra to enable validation
mcp_registry load_registry (mtime-invalidated cache), resolve_server, check_approval, McpServerRecord, ApprovalVerdict MCP server registry — resolution layer for architecture/mcp-server-registry-1029.md (issue #40), mirroring how config resolves config-conventions. Platform single source of truth for which MCP tool servers are approved (status lifecycle proposed → reviewed → approved → deprecated; only approved may be referenced). JSON sidecar architecture/mcp-server-registry.json (stdlib json, zero new deps; mirrored as bundled fusion_core/mcp-server-registry.json for pip installs / CI — edit all three plus the md table). check_approval(url, tool_scope) returns a verdict — result, not error (E5 pattern): url-prefix match (same semantics as cowork Permission.matches url: scopes, trailing slashes normalized), longest prefix wins, non-approved status → denied, tool scope exact / * / ns.* wildcard, no url match → unknown (per-URL operator approval decides). Credential mode is declaration only (identity_issuance / env_ref) — no secrets stored, no network calls, no MCP client, no enforcement defaults (callers decide warn vs block). Malformed registry → RegistryIntegrityError (fail visibly). Default path from FUSION_MCP_REGISTRY, resolved lazily at call time
mcp_client McpToolClient, McpToolError, known_servers Thin stdio JSON-RPC client for MCP tool servers (issue #42), paired with mcp_registry: registry resolves which servers exist and are approved, client calls them. Pure move from ai-doc-automation. known_servers() returns name -> McpServerRecord for proposed/approved servers declaring a stdio_command; McpToolClient.call_tool(tool, arguments, timeout_s=30) speaks minimal JSON-RPC over stdio (initialize → notifications/initialized → tools/call), spawn-per-call, returns {"ok": bool, "text": str, "raw": result} — isError is a result, not an error (E5 pattern); transport/protocol/timeout failures raise McpToolError. stdio_command.env values with an env:VAR prefix resolve from the operator's environment at call time — credentials never stored in the registry. Registry path through mcp_registry.default_registry_path() (FUSION_MCP_REGISTRY env → monorepo sidecar → bundled copy). stdio only (no HTTP/SSE), no registry writes; import stays I/O-free
errors FusionError Shared error tree base (issue #47). Class-level defaults code / http_status / remediation, overridable per raise; structured context copied at construction; to_http() returns a sanitized {status, code, message, remediation, context} payload for API error handlers. Wrap upstream failures with raise ... from so the chain stays intact. Replaces private per-app error trees
proc set_process_title Process-title helper (issue #30). setproctitle is the only reliable title mechanism on macOS (Python.app overwrites argv[0]); fail-open — title is cosmetic, a missing setproctitle logs at DEBUG and never blocks service startup. Lazy import inside the function keeps import fusion_core I/O-free and setproctitle out of sys.modules; install [proc] extra to enable

Usage

LLM chat + JSON parse

from fusion_core import create_async_client, parse_llm_json, get_logger

log = get_logger(__name__)

client = create_async_client(
    base_url="http://localhost:11434",
    api_key="...",
    model="qwen2.5-7b",
)
resp = await client.chat(messages=[{"role": "user", "content": "Return JSON"}])
data = parse_llm_json(resp.content)  # invalid JSON raises ParseError, not silent {}

Streaming (with mid-stream recovery envelope)

collected = []
try:
    async for chunk in client.stream_chat(messages=[...]):
        collected.append(chunk)
except StreamError as e:
    # ALL stream-failure paths raise StreamError (H4/R4): mid-stream severed
    # (e.delivered > 0) OR retriable-exhausted-no-output (e.delivered == 0).
    # Non-retriable 4xx raise HTTPStatusError instead (bad request, not severed).
    log.warning("stream severed after %d chars, resume at %d", e.delivered, e.resume_offset)

End-to-end deadline

# total_deadline caps the whole retry budget, not just one request
resp = await client.chat(messages=[...], total_deadline=30.0)

Hand retry off to fusion-gateway (avoid double-retry)

from fusion_core import with_retry

# when fusion-gateway's circuit breaker owns retry, disable core's own retry.
# verify_gateway=True probes gateway /readyz first; if the breaker is open or
# the gateway is unreachable, core falls back to its own retry (H3/E4 — no
# capability vacuum).
resp = await with_retry(fn, disable=True, verify_gateway=True)

FastAPI factory

from fusion_core.http import create_app, install_auth

# cors_credentials defaults False; "*" with credentials=True raises ValueError
app = create_app("my-svc", cors_origins=["https://example.com"], cors_credentials=True)
install_auth(app, api_keys=["secret"])  # request_id is outermost middleware; 401 also carries it

Zero-trust guard client (fusion-guard)

from fusion_core import FusionGuardClient

# default socket /tmp/fusion-guard.sock; override via FUSION_GUARD_SOCK or ctor.
with FusionGuardClient() as guard:
    verdict = guard.evaluate("rm -rf /", caller_epoch=guard.ping()["rules_epoch"])
    if verdict.action == "block":
        # a block is a normal verdict, NOT an exception — inspect .action (E5).
        log.warning("blocked: %s (risk %s)", verdict.reason, verdict.risk_level)
    rules, epoch = guard.list_rules()
    redacted = guard.redact("my SSN is 123-45-6789")
    chain = guard.audit_verify()  # tamper-evidence across audit/tcc/rules/dead_letter

Embeddings

resp = await client.embed("hello world", model="bge-m3")
print(resp.vector)  # single input → .vector
batch = await client.embed(["a", "b"], model="bge-m3")
print(batch.vectors)  # batch input → .vectors list

Design principles

  • Pure tech, zero business: no K12 grading, no finance thresholds, no medical contraindications, no DAG nodes. When a boundary is blurry, it stays out.
  • Non-invasive, standalone: fusion_core imports on its own, depends on no other fusion-* project.
  • Fail visibly, no fallbacks: parse_llm_json raises instead of returning {}; client failure raises instead of returning empty content; get_server_stats failure raises instead of returning {}.
  • Tests are isolatable: -m 'not integration' skips real-engine tests; integration fixtures record was_running and only stop engines they started.

Boundary declaration — cluster capabilities belong to fusion-gateway

fusion-core is a single-process, single-engine client library, not a cluster control plane. The PRD §0.2 four iron rules (pure tech / non-invasive / fail-visible / isolatable tests) draw the boundary. The cluster-level capabilities below are already implemented and live in fusion-gateway (Go, :11432) — core does not rebuild them (rebuilding = duplication + violates "pure tech, zero business"). Core only does the minimal "don't conflict with gateway behavior" fixes.

Capability gateway implementation core action
Endpoint registry / routing / failover discovery (node register/health/evict) + router/engine default_mlx_base_url() reads FUSION_MLX_URL; point at gateway for multi-node
Circuit breaker router/circuit_breaker.go:CircuitBreaker with_retry(disable=True) disables core retry, hands to gateway breaker, avoids double-retry
Per-endpoint concurrency gate router/engine.go:MaxConcurrent core pool adds no concurrency cap
Model registry model→endpoint router routes by model caller passes model, gateway resolves endpoint; core holds no topology
Metrics (Prometheus) observability/metrics (circuitBreakerState/Trips, routeDecisions, requestDuration, requestTotal) core does not double-instrument (http_client metrics callback kept for single-process use)
Agent scheduling (slots/queue/cancel) routing-layer concurrency governance scheduling is business orchestration → fusion-cowork / agent-studio

Multi-node access: export FUSION_MLX_URL=http://<gateway-host>:11432/v1 — core then hits the gateway, which routes to cluster nodes. Core itself is always a single base_url view.

See audit/fusion-core-audit-report-0824.md §六 for the landing state.

Migration guide (self-built client → fusion-core)

Projects still on bare httpx to MLX (no retry/timeout/metrics): fusion-health, fusion-science, fusion-rag, fusion-simulation, fusion-code-modelization, fusion-security, fusion-trainer.

Steps (one PR per project, see architecture/venv-fix-0823.md §5):

  1. httpx.AsyncClient.post(.../chat/completions) → create_async_client(...) + await client.chat(...)
  2. Self-built _parse_json → parse_llm_json (raises on failure, not return {})
  3. No base_url → uses core default localhost:11434/v1 (aligned with fusion-mlx start.sh, not the gateway)
  4. Silent degrade return LLMResult(content="", error=...) → raise (fixes audit D-H3 silent failure)
# Before (health llm_gateway.py silent failure)
try:
    resp = await client.post(f"{url}/chat/completions", ...)
    return LLMResult(content=resp.json()["choices"][0]["message"]["content"])
except Exception as e:
    return LLMResult(content="", error=str(e))  # silent! downstream proceeds on empty

# After
from fusion_core import create_async_client

self._client = create_async_client(base_url=url, api_key=key, model=model)
result = await self._client.chat(messages=messages)  # raises on failure
return LLMResult(content=result.content, model=result.model)

PRD §7.1 acceptance (measured, not declared)

Acceptance item Status Evidence
import fusion_core triggers no I/O (no env/file/conn) ✅ mlx_client dropped module-level os.environ.get; resolves default_mlx_base_url() at call time; tests/test_config.py::TestImportTimeIsolation guards with env-get spy
grep source has no or {} / or [] / or "" silent fallback ✅ resolve_api_key dropped or ""; get_server_stats raises, not return {}
LLM client holds no retry logic (single responsibility) ✅ mlx_client.chat routes to http_client.with_retry; single source RETRY_STATUS/RETRY_EXCEPTIONS
Integration tests hit 11434 (PRD §7.1) ✅ DEFAULT_MLX_PORT = 11434, aligned with fusion-mlx start.sh; integration fixture was_running doesn't kill user's engine
CORS *+credentials rejected ✅ create_app(cors_origins=["*"], cors_credentials=True) raises ValueError; credentials defaults False

Testing

pytest tests/ -m "not integration"   # unit: 393 passed, 1 skipped (env-only)
pytest tests/ -m integration          # real fusion-mlx engine: 7 passed, 0 skipped
ruff check . && ruff format --check . # lint clean

Documentation

  • 中文文档 (Chinese)
  • Module reference: docs/ — per-module API signatures, params, returns, exceptions, examples
  • Audit: ../audit/fusion-core-audit-report-0824.md — 28 findings, 21 core fixes + 7 boundary declarations
  • PRD: ../architecture/fusion-core-prd-0823.md

Related

  • Fix plan: ../architecture/venv-fix-0823.md §5 (client rollout)
  • Audit: ../audit/fusion-audit-all-report.md Chapter 4 Q1
  • Production-readiness audit: ../audit/fusion-core-audit-result-product-0827.md
  • License: Apache-2.0

About

Fusion shared core library - unified FusionMLXClient for Python projects

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages