Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
402983b
feat(gateway): add Rust PowerContext Gateway executor
ztelur Oct 29, 2026
153b8b6
style(gateway): clippy clean — desugar impl-Future wrappers to async fn
ztelur Oct 29, 2026
9ffe018
docs(gateway): document features and the PC UDS call sequence
ztelur Oct 29, 2026
0572eca
fix(gateway): harden gate semantics from code review
ztelur Oct 29, 2026
4930845
chore(gateway): add Apache-2.0 license headers to all source files
ztelur Oct 30, 2026
b87c096
fix(gateway): never retry requests already handed to the upstream
ztelur Oct 30, 2026
5a89508
fix(gateway): disable automatic upstream redirects
ztelur Oct 30, 2026
4faa44b
fix(gateway): preserve Chat tool-call metadata through canonicalization
ztelur Oct 30, 2026
9c4a129
fix(gateway): keep Responses text content in a valid wire shape
ztelur Oct 30, 2026
301d54e
fix(gateway): apply the response buffer limit to nonstreaming calls
ztelur Oct 30, 2026
007aa23
style(gateway): drop narrative comment at the redirect policy
ztelur Oct 31, 2026
a0b9cb0
fix(gateway): enforce the configured body limit on chunked requests
ztelur Oct 31, 2026
88c0dc4
chore: remove accidentally committed stale gateway copy
ztelur Oct 31, 2026
26d944e
ci(gateway): build, lint, and test the Rust workspace
ztelur Oct 31, 2026
ec87119
ci(gateway): adopt the post-#2285 ci-paths structure
ztelur Oct 31, 2026
bde6925
fix(gateway): enforce admission validity and safe degradation (P1-3, …
ztelur Nov 1, 2026
2c6d7e5
fix(gateway): CI checks entry, fail-closed valid_until, capture re-ch…
ztelur Nov 1, 2026
4788f27
ci: adopt current master ci-paths.toml with gateway entries
ztelur Nov 1, 2026
2f1327d
fix(gateway): preserve supported Chat request controls through rendering
ztelur Nov 1, 2026
7f2bcf2
Merge branch 'master' into feat/rust-gateway
ztelur Nov 1, 2026
edc22e6
fix(gateway): Responses structured output via text field, not respons…
ztelur Nov 1, 2026
7e0c353
test(gateway): probe tests for unparseable valid_until and capture-ex…
ztelur Nov 1, 2026
d4b657f
fix(gateway): apply the configured body limit to the proxy path
ztelur Nov 1, 2026
0268866
fix(gateway): preserve Responses store field and restrict reuse to me…
ztelur Nov 1, 2026
e59f16c
test(gateway): probe tests for store field and memory-only assembly
ztelur Nov 1, 2026
841abac
fix(gateway): hold concurrency permit for streaming responses; valida…
ztelur Nov 2, 2026
c5262d9
test(gateway): probe tests for malformed allow validation
ztelur Nov 2, 2026
93519d9
fix(gateway): route destination safety, rejection semantics, data pro…
ztelur Nov 2, 2026
6406eaf
fix(gateway): preserve token limits, validate contract versions, conf…
ztelur Nov 2, 2026
1e8c12a
fix(gateway): preserve typed user text in recall query and transcript
ztelur Nov 2, 2026
065ed24
fix(gateway): cumulative UDS budget, earliest SSE separator, token-li…
ztelur Nov 2, 2026
2e839cb
ci(gateway): align gateway workflow with the master orchestrator pattern
ztelur Nov 2, 2026
6a42753
fix(gateway): workflow permissions, typed-content injection, UDS budg…
ztelur Nov 2, 2026
d05f4e6
fix(gateway): token_limit_field conditionally set in Chat ingress; en…
ztelur Nov 2, 2026
92dafe8
fix(gateway): preserve non-text parts when injecting into typed content
ztelur Nov 2, 2026
c2919d6
fix(gateway): single-injection for multi-text parts, typed pointer, U…
ztelur Nov 2, 2026
4e55672
fix(gateway): cumulative UDS chunk budget before reading chunk data
ztelur Nov 2, 2026
6075cc6
fix(gateway): capture and pass through the Responses conversation par…
ztelur Nov 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions gateway/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
target/
Cargo.lock
.DS_Store
42 changes: 42 additions & 0 deletions gateway/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[workspace]
resolver = "2"
members = [
Comment thread
ztelur marked this conversation as resolved.
Resolved
"crates/pc-gateway-app",
"crates/pc-gateway-core",
"crates/pc-gateway-types",
"crates/pc-gateway-protocol",
"crates/pc-gateway-transport",
"crates/pc-gateway-evidence",
"crates/pc-gateway-embedded",
]

[workspace.package]
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
repository = "https://github.com/oceanbase/powercontext"

[workspace.dependencies]
pc-gateway-core = { path = "crates/pc-gateway-core" }
pc-gateway-types = { path = "crates/pc-gateway-types" }
pc-gateway-protocol = { path = "crates/pc-gateway-protocol" }
pc-gateway-transport = { path = "crates/pc-gateway-transport" }
pc-gateway-evidence = { path = "crates/pc-gateway-evidence" }

tokio = { version = "1", features = ["full"] }
axum = "0.7"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
bytes = { version = "1", features = ["serde"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
hyper = { version = "1", features = ["client", "http1"] }
tower = { version = "0.5", features = ["util"] }
hyper-util = { version = "0.1", features = ["client", "client-legacy", "tokio", "http1"] }
http-body-util = "0.1"
futures-core = "0.3"

[profile.release]
lto = "thin"
98 changes: 98 additions & 0 deletions gateway/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# PowerContext Rust Gateway

An optional Rust executor for PowerContext, defined by the gateway design in #2199 and the context-protection contract in #2264. The gateway owns the model traffic boundary; every decision stays in PowerContext Core ("no policy in the gateway").

> Status: working prototype, verified end-to-end against a real PowerContext Server (PR #2264 branch) with real upstream providers (GLM, DeepSeek). Depends on the `/v1/context/check` contract and `include_reuse` from #2264.

## Features

### Model traffic pipeline (per request)

- **Two-phase gate executor**: `check(before_send)` → send admitted bytes → `check(before_release)` → release. Opaque bindings thread the two phases (`request_binding` must be the send-phase binding). HTTP success alone is never treated as approval; unknown never becomes allow.
- **Privacy enforcement by Core, executed by the gateway**: forbidden content is blocked before any byte leaves the gateway (zero-send on block/withhold, zero-release on refuse, upstream cancel on refusal).
- **Deterministic-failure-only bounded retry**: connection-refused style failures retry a bounded number of times with a single owner; indeterminate outcomes (timeout after hand-off) are surfaced as `send_indeterminate` and never auto-retried (no paid re-sends).
- **Degradation policy**: when Core is unreachable, either pause (default) or pass through without memory (`PC_GATEWAY_DEGRADE=passthrough`) — degraded responses are explicitly marked (`x-pc-degraded` header). Blocked verdicts never degrade.
- **Streaming ingestion** (`stream: true`): upstream SSE is received incrementally (TTFT measured, byte-capped); strict semantics hold — the complete raw response is buffered and must pass `before_release` before anything is released to the client. (The current public carrier in #2264 withholds streaming payloads; the pipeline is ready for when the contract allows it.)
- **Status-code fidelity**: upstream errors pass through with their original status code (a provider 402/400 is never masked as 200), and `Content-Type` is preserved.

### Memory features (#2199 capabilities)

- **Auto-recall injection**: for each new user message the gateway calls `prepare` with `include_reuse`, and injects the returned prepared context **verbatim** into the current user message. The exact UTF-8 byte range is declared in `prepared_contexts` (`ModelJsonTextLocation`); Core verifies the digest of the declared range against the signed reuse binding — a single byte changed by the gateway is rejected. Empty or failed prepares inject nothing and never block the main path. Injection is tail-only (current message), so the client-owned history prefix stays byte-stable (KV prefix-cache friendly, verified with DeepSeek `cached_tokens`).
- **Sedimentation**: after a released turn, the gateway synchronously captures the transcript via `capture_content_source` (millisecond-scale durable write; extraction happens later in PC background workers). `source_id` is idempotent (derived from the release binding digest). Blocked and degraded turns are never captured. The full loop — conversation → capture → background extraction into Atomic Memory → `prepare` recall in a *new* session — has been verified end-to-end.

### Deployment & ops

- **Two deployment forms**: *combined* (Rust owns the public TCP port; Core listens only on a private Unix socket; all non-`/gateway` routes are reverse-proxied to Core over UDS) or *standalone* (TCP to a remote Core).
- **UDS client**: hand-rolled HTTP/1.1 over the Unix socket with a pooled, keep-alive connection pool (bounded idle set, connect/read timeouts, stale-connection single retry, content-length truncation and chunked-trailer consumption — covered by a real-socket regression test).
- **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), authenticated by a gateway key that replaces provider keys.
- **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (request-body precheck + concurrency semaphore, health probe exempt) and request-id propagation (`x-powercontext-request-id`, client-supplied or generated, echoed on responses).
- **Body-free evidence**: usage completeness (known/estimated/unknown), cache tokens, TTFT vs first-release latency, attempt counters — never request/response bodies.

## PC call sequence over UDS

All gateway→Core calls go through one `GateClient` (UDS in combined form, TCP in standalone form) and share the connection pool. For one chat request with injection and sedimentation enabled:

```
client ──POST /gateway/v1/chat/completions──▶ gateway (middleware: limits → request-id)
│
1. prepare gateway ──▶ POST /v1/context/prepare (query = last user message,
◀── include_reuse=true)
content (trust preamble + marker block) + reuse binding (5 min)
— injected verbatim; byte range recorded; failure/empty ⇒ no injection
│
2. check gateway ──▶ POST /v1/context/check phase=before_send
(send gate) ◀── allow + send binding (60 s) | block/withhold ⇒ 403/409, zero send
│
3. send gateway ──▶ upstream provider (admitted bytes only; the single egress)
◀── complete raw response (+ usage)
│
4. check gateway ──▶ POST /v1/context/check phase=before_release
(release (payload = complete raw response, request_binding = send binding)
gate) ◀── allow + release binding | refuse ⇒ cancel upstream, 403,
nothing released
│
5. capture gateway ──▶ POST /v1/sources/content (transcript JSON,
◀── source_id = digest(release binding)) — released turns only;
failure is evidence-only
│
client ◀── 200 (upstream status/content-type preserved, request-id echoed) ── gateway
```

Everything else (Core's 127 domain operations, MCP, dashboard) is reverse-proxied to Core over the same UDS socket, untouched by gateway logic.

## Layout

| Crate | Responsibility |
| --- | --- |
| `pc-gateway-app` | thin binary: ingress, port-takeover proxy, middleware chain |
| `pc-gateway-core` | executor state machine, GateClient (check/prepare/capture/capabilities) over TCP or UDS |
| `pc-gateway-types` | contract DTOs aligned field-by-field with #2264 |
| `pc-gateway-protocol` | canonical request, chat/responses wire renderers, SSE framing |
| `pc-gateway-transport` | upstream transport, bounded retry, streaming buffer with caps |
| `pc-gateway-evidence` | body-free evidence (usage completeness, cache tokens, TTFT) |
| `pc-gateway-embedded` | placeholder for the in-process (FFI) executor path |

## Run

```bash
cargo build --release

# Combined deployment (Core on a Unix socket)
PC_GATEWAY_CORE_UDS=/path/to/pc.sock \
PC_GATEWAY_UPSTREAM_PROFILE=<approved profile name> \
PC_GATEWAY_DEFAULT_SCOPE=<scope id> \
PC_GATEWAY_UPSTREAM_URL_CHAT=https://provider/v1/chat/completions \
PC_GATEWAY_UPSTREAM_API_KEY_CHAT=... \
./target/release/pc-gateway

# Optional: PC_GATEWAY_INJECTION=on (prepare + inject), PC_GATEWAY_SEDIMENT=on (capture after release),
# PC_GATEWAY_DEGRADE=passthrough (no-memory passthrough when Core is unreachable; never applies
# to deployments with enforcing protection), PC_GATEWAY_MAX_CONCURRENT / PC_GATEWAY_MAX_BODY_BYTES,
# PC_GATEWAY_CORE_TOKEN (bearer for Core when authentication is enabled).
```

Credentials live only in server-side environment variables; they are never accepted from request fields and never enter check payloads.

## Tests

`cargo test` — 27 tests covering the failure-semantics table (gate unavailable, withhold terminal, bounded retry, indeterminate no-resend, blocked turns never sediment), renderer fidelity (no timestamps/request ids injected), byte-range declaration, UDS connection-pool correctness over a real Unix socket, and live integration tests against a real PowerContext Server (binding validity, cross-scope rejection, deadlines) that skip gracefully when no server is reachable.
29 changes: 29 additions & 0 deletions gateway/crates/pc-gateway-app/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[package]
name = "pc-gateway-app"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "PowerContext Gateway: thin binary — port takeover, Core/MCP forwarding, OpenAI-compatible model ingress"

[[bin]]
name = "pc-gateway"
path = "src/main.rs"

[dependencies]
pc-gateway-core = { workspace = true }
pc-gateway-types = { workspace = true }
pc-gateway-protocol = { workspace = true }
pc-gateway-transport = { workspace = true }
pc-gateway-evidence = { workspace = true }
bytes = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
axum = { workspace = true }
serde_json = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
reqwest = { workspace = true }
hyper = { workspace = true }
tower = { workspace = true }
hyper-util = { workspace = true }
http-body-util = { workspace = true }
Loading
Loading