From 17141894cd26832a32f69c6b245351a295038826 Mon Sep 17 00:00:00 2001 From: frf12 Date: Sun, 22 Nov 2026 23:35:14 +0800 Subject: [PATCH] feat(gateway): enable steering and memory defaults --- docs/en/docs/operate/deploy-server.md | 12 +- .../design/atomic_memory_one_pass_design.md | 12 +- docs/zh/docs/operate/deploy-server.md | 12 +- gateway/README.md | 6 +- .../pc-gateway-app/src/default_steering.txt | 1 + gateway/crates/pc-gateway-app/src/main.rs | 36 +++-- gateway/crates/pc-gateway-app/src/steering.rs | 20 ++- .../pc-gateway-app/tests/gateway_behaviors.rs | 152 ++++++++++++++++++ src/powercontext/server/settings.py | 13 ++ tests/test_server_generation.py | 81 +++++++++- 10 files changed, 314 insertions(+), 31 deletions(-) create mode 100644 gateway/crates/pc-gateway-app/src/default_steering.txt diff --git a/docs/en/docs/operate/deploy-server.md b/docs/en/docs/operate/deploy-server.md index ae2658788e..5c9c993bf8 100644 --- a/docs/en/docs/operate/deploy-server.md +++ b/docs/en/docs/operate/deploy-server.md @@ -200,7 +200,9 @@ Set `PC_GATEWAY_INJECTION_CODE=on` to include code evidence from the Scope's cod ### Gateway instruction -`PC_GATEWAY_STEERING_FILE` names a file with a short, fixed instruction that the gateway adds to every request on the Responses route (`/gateway/v1/responses`); the Chat route is never changed. The gateway reads the file once at startup. It must be UTF-8, non-empty after trimming, at most 4,096 bytes, and free of PowerContext's reserved `BEGIN_POWERCONTEXT_` markers; otherwise the gateway exits at startup instead of running without it. Nothing is added when the variable is unset. +The gateway adds a built-in cost-guidance instruction (S) to every request on the Responses route (`/gateway/v1/responses`) by default; the Chat route is never changed. The text encourages targeted searches, batched reads, concise edits, and focused validation. `PC_GATEWAY_STEERING=off` disables it; unset or `on` enables it. Other values prevent startup. + +`PC_GATEWAY_STEERING_FILE` replaces the built-in text with a custom instruction. When steering is enabled, the gateway reads the file once at startup. It must be UTF-8, non-empty after trimming, at most 4,096 bytes, and free of PowerContext's reserved `BEGIN_POWERCONTEXT_` markers; otherwise the gateway exits at startup instead of running with a different instruction. `PC_GATEWAY_STEERING=off` takes precedence and does not read the file. The text becomes the first content block of the developer message that follows the client's first developer message, which is where Codex places its own `developer_instructions`. Without such a message, the gateway inserts a new developer message after the client's first developer message, or before the first user message when the request has no developer message. The text is identical on every request, so it stays part of the cached prefix. Core checks it as part of the final request like any other request text. It is independent of context injection, capture, and replay. @@ -221,9 +223,9 @@ These are per-body and per-class concurrency limits. They do not measure retaine ### Memory extraction over the cached prefix When the gateway runs on the same host as the Server, Atomic Memory extraction for a captured turn can reuse the -provider's prompt cache for the agent's conversation instead of sending the transcript again. OAuth subscription traffic uses normal extraction. Prefix extraction is off by default and needs both sides: +provider's prompt cache for the agent's conversation instead of sending the transcript again. The gateway enables prefix extraction by default for non-subscription upstreams; `PC_GATEWAY_PREFIX_EXTRACTION=off` disables it, and `on` explicitly enables it. Other values prevent startup. Native OAuth subscription traffic still does not support this extraction path, even with `on`. Capture and the Server callback must also be configured: -- **Gateway:** `PC_GATEWAY_PREFIX_EXTRACTION=on` together with capture (`PC_GATEWAY_SEDIMENT=on`). For a Responses +- **Gateway:** Enable capture with `PC_GATEWAY_SEDIMENT=on`; capture remains off by default. For a Responses conversation, the gateway keeps the exact request it sent and the response output of each turn's final response in memory, for at most 30 minutes, at most 64 turns and at most 64 MiB in total; the oldest are dropped first, and a turn dropped before extraction goes through normal extraction. It records an opaque handle in the captured Source's metadata, @@ -251,6 +253,10 @@ provider's prompt cache for the agent's conversation instead of sending the tran `POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_GATEWAY_HEADERS` set to `{"Authorization": "Bearer "}` when the gateway requires a key. A generation model is still required, because normal extraction is the fallback. +With `POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_GATEWAY_URL` configured, the Server defaults Atomic Memory processing to `one_pass` unless a mode was explicitly supplied. Set `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=per_candidate` to retain per-candidate extraction, or `one_pass` to select one-pass explicitly. A Server without the callback URL and direct SDK configurations keep their existing `per_candidate` default. The gateway cannot discover or configure this URL for a separately started Server. + +One-pass reuses its own memory-generation conversation across steps. Its normal path does not reuse the agent's captured prefix. The prefix-extraction path below applies to per-candidate processing, including one-pass input-budget fallback; enabling both settings does not combine their cache benefits or guarantee a cache hit. + Cached input is not free: the provider still bills it at a reduced rate. When a processing window holds exactly one such turn, the Server first estimates both requests. The prefixed request costs Core's instruction plus the final response's output tokens at the full rate, plus the cached input tokens multiplied by diff --git a/docs/zh/design/atomic_memory_one_pass_design.md b/docs/zh/design/atomic_memory_one_pass_design.md index 4c25f7e628..363bf5cdf0 100644 --- a/docs/zh/design/atomic_memory_one_pass_design.md +++ b/docs/zh/design/atomic_memory_one_pass_design.md @@ -2,7 +2,7 @@ | 项 | 内容 | | --- | --- | -| 特性类型 | 原子记忆的可选处理模式,**默认关闭** | +| 特性类型 | 原子记忆处理模式;配置网关回连的 Server 默认开启,其余场景保持逐候选默认 | | 对外契约 | 不新增 HTTP API,不改 OpenAPI,不改持久化格式,不新增提示词 key | | 新增配置 | 一个 Server 运行时配置项,选择原子记忆处理模式 | | 文档状态 | 已实现,评测结果见 §6 | @@ -18,7 +18,7 @@ 可以命中模型服务的前缀缓存,因此不再为每条候选重复发送整段 Source。 它作为可选模式提供:在两个评测集上,成本是现有流程的 20%–31%,存储条数与现有流程接近, -编码场景的事实覆盖度持平,对话场景的问答准确率不低于现有流程(见 §6)。默认模式不变,替换默认模式的条件见 §8。 +编码场景的事实覆盖度持平,对话场景的问答准确率不低于现有流程(见 §6)。配置网关前缀抽取回连地址的 Server 默认使用单次整理,显式配置仍优先;SDK 与未配置网关回连的 Server 保持逐候选默认。全面替换默认模式的条件见 §8。 ## 1. 约束 @@ -28,7 +28,7 @@ | C2 | 溯源不变:每条发布的记忆仍带正确的 `sources` | 第 2 步的每个操作给出 `evidence_ids`,Core 校验后按现有方式计算 `sources` | | C3 | 校验与读依赖不变 | 每个 revise / merge 转换为 `AtomicMemoryReconciliationOutput` 后由 `workset.apply()` 校验;展示过的已有记忆全部记入 workset 的读依赖,发布时照常做冲突检查 | | C4 | 提示词配置不分裂:用户仍只维护 `atomic_memory.extract` 与 `atomic_memory.reconcile` | 流程指令是代码常量;两个 key 的现有配置嵌入其中(§4) | -| C5 | 默认行为字节级不变 | 未开启时不进入任何新代码路径 | +| C5 | 显式模式优先,默认值按部署配置选择 | 网关回连已配置且模式未指定的 Server 使用单次整理;其余默认与显式逐候选模式保留原流程 | ## 2. 现有流程(master) @@ -143,7 +143,7 @@ Core 在应用时记录本次回复已写过的记忆,再次以 revise / merge ### 5.1 配置 `RuntimeConfig` 新增 `atomic_memory_processing_mode: Literal["per_candidate", "one_pass"] = "per_candidate"`, -对应环境变量 `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE`,中英文配置文档已同步。 +对应环境变量 `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE`。Server 配置了 `inference.prefix_extraction_gateway_url` 且未显式指定模式时,解析后的运行时默认值为 `one_pass`;显式 `per_candidate` 或 `one_pass` 均优先。SDK 的 `RuntimeConfig` 默认值不变,完整配置序列化中的具体模式也按显式设置处理。 `AtomicMemoryProcessingConfig.from_runtime()` 读取该值。第 1 步的项数上限(30)、每个检索词展示的记忆数(5) 与展示总数上限(40)是 `one_pass.py` 中的常量。 @@ -258,7 +258,7 @@ Core 在应用时记录本次回复已写过的记忆,再次以 revise / merge 5. **其他模型服务的前缀缓存。** 成本数据来自一个支持自动前缀缓存的模型服务。不支持前缀缓存、或需要显式 标记缓存位置的服务上,成本收益会小于 §6.2。 -## 8. 替换默认模式的条件 +## 8. 全面替换默认模式的条件 同时满足以下条件后,再讨论把单次整理设为默认: @@ -268,7 +268,7 @@ Core 在应用时记录本次回复已写过的记忆,再次以 revise / merge - 存储条数与每条记忆的长度和现有流程接近。 以上各项在 §6 的评测中已满足。评测只覆盖一个模型服务、内置抽取规则和单 Source 窗口(§7), -在这些条件之外重复得到同样结果后,再提出替换默认模式。 +当前默认切换仅适用于已配置网关回连地址、且未显式指定模式的 Server。在这些条件之外重复得到同样结果后,再提出替换 SDK 与其他 Server 场景的默认模式。 ## 附录 A:流程指令 diff --git a/docs/zh/docs/operate/deploy-server.md b/docs/zh/docs/operate/deploy-server.md index 82d150c086..d560acac9b 100644 --- a/docs/zh/docs/operate/deploy-server.md +++ b/docs/zh/docs/operate/deploy-server.md @@ -202,7 +202,9 @@ Gemini 关闭 Gateway 上下文注入。Claude CLI 只接受新的单轮文本 ### 网关固定指令 -`PC_GATEWAY_STEERING_FILE` 指定一个文件,其中是一段简短的固定指令,网关把它加入 Responses 入口(`/gateway/v1/responses`)的每个请求;Chat 入口的请求不受影响。网关只在启动时读取一次该文件。文件必须是 UTF-8,去掉首尾空白后不能为空,不超过 4096 字节,并且不能含有 PowerContext 保留的 `BEGIN_POWERCONTEXT_` 标记;否则网关在启动时退出,而不是不带指令运行。未设置该变量时不加入任何内容。 +网关默认向 Responses 入口(`/gateway/v1/responses`)的每个请求加入内置的成本指导指令(S),提示模型定向搜索、合并读取、集中修改并进行针对性验证;Chat 入口不受影响。`PC_GATEWAY_STEERING=off` 关闭指令;未设置或设为 `on` 时开启,其他值会阻止启动。 + +`PC_GATEWAY_STEERING_FILE` 用自定义指令替换内置文本。开启指令时,网关只在启动时读取一次该文件。文件必须是 UTF-8,去掉首尾空白后不能为空,不超过 4096 字节,并且不能含有 PowerContext 保留的 `BEGIN_POWERCONTEXT_` 标记;否则网关在启动时退出,不会改用其他指令。`PC_GATEWAY_STEERING=off` 优先于文件配置,关闭时不读取文件。 指令文本成为客户端第一条 developer 消息之后那条 developer 消息的第一个内容块,也就是 Codex 放置自身 `developer_instructions` 的位置。没有这样的消息时,网关在客户端第一条 developer 消息之后插入一条新的 developer 消息;请求中没有 developer 消息时,插在第一条用户消息之前。每个请求中的文本都相同,因此它始终是缓存前缀的一部分。Core 把它作为最终请求的一部分,像其他请求文本一样检查。它与上下文注入、沉淀和重放相互独立。 @@ -223,9 +225,9 @@ Rust Gateway 在启动时通过 `/v1/capabilities` 查询一次 `context_protect ### 复用缓存前缀抽取记忆 网关与 Server 部署在同一主机时,为一个已沉淀回合抽取 Atomic Memory 可以复用服务商为 Agent 会话写下的提示缓存, -而不必再次发送对话记录。OAuth 订阅流量使用普通抽取。前缀抽取默认关闭,需要两端同时开启: +而不必再次发送对话记录。网关对非订阅上游默认开启前缀抽取;`PC_GATEWAY_PREFIX_EXTRACTION=off` 关闭,`on` 显式开启,其他值会阻止启动。原生 OAuth 订阅流量仍不支持这条抽取路径,即使设置 `on` 也不会开启。还需配置沉淀与 Server 回连: -- **网关:** 设置 `PC_GATEWAY_PREFIX_EXTRACTION=on`,并开启沉淀(`PC_GATEWAY_SEDIMENT=on`)。对 Responses 会话,网关 +- **网关:** 设置 `PC_GATEWAY_SEDIMENT=on` 开启沉淀;沉淀仍默认关闭。对 Responses 会话,网关 在内存中保留每个回合终止响应对应的、实际发出的请求及其响应输出,最多 30 分钟、最多 64 个回合、总计最多 64 MiB, 超出时先丢弃最早的,抽取前已被丢弃的回合走普通抽取;并在沉淀的 Source 元数据中记录一个不透明的句柄,以及该终止响应的输入和输出 token 数。请求和响应本身从不进入 Source、证据或日志。 @@ -245,6 +247,10 @@ Rust Gateway 在启动时通过 `/v1/capabilities` 查询一次 `context_protect 将 `POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_GATEWAY_HEADERS` 设为 `{"Authorization": "Bearer "}`。仍需配置生成模型,因为普通抽取是回退路径。 +配置 `POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_GATEWAY_URL` 后,Server 在没有显式指定处理模式时默认使用 `one_pass` 整理 Atomic Memory。设置 `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=per_candidate` 可保留逐候选处理,设为 `one_pass` 可显式选择单次整理。未配置回连地址的 Server 和直接使用 SDK 的配置仍默认使用 `per_candidate`。网关不会替独立启动的 Server 自动发现或配置这个地址。 + +one-pass 在各步骤间复用的是记忆生成自身的对话,正常路径不会复用 Agent 已捕获的原始前缀。下述前缀抽取路径用于逐候选处理,也包括 one-pass 输入超预算后回退到逐候选的情况;同时开启两项配置不代表两种缓存收益叠加,也不保证命中缓存。 + 命中缓存的输入并非免费,服务商仍按较低的价格计费。处理窗口恰好只含一个这样的回合时,Server 先估算两种请求的成本: 前缀请求为 Core 的指令加上终止响应的输出 token(按全价),再加上命中缓存的输入 token 乘以 `POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_CACHED_INPUT_RATIO`(默认 `0.1`);普通抽取为其指令加上 Source diff --git a/gateway/README.md b/gateway/README.md index 2d6d5d762b..d2b138f11e 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -20,7 +20,11 @@ Use `X-PowerContext-Conversation-ID` to identify a conversation. The Gateway als Set `PC_GATEWAY_SEDIMENT=on` to capture completed user turns as Sources for later extraction. Capture excludes injected context and provider reasoning ciphertext. Tool continuations remain open until the final response. Long turns are split into Sources, and Core stores all parts in one batch. With a trusted conversation ID, captures share a turn digest and include a digest of the ordered normalized Source parts in their Source IDs. Distinct terminal records are stored independently; identical normalized parts are idempotent even when provider response IDs or usage change. Existing Sources remain unchanged, and a repeated capture under the former turn-only ID creates a new Source. Capture requires a Core that supports batch capture. Capture failure does not prevent response delivery. Blocked and degraded turns are not captured. -For a Responses upstream configured without a subscription, `PC_GATEWAY_PREFIX_EXTRACTION=on` lets Core reuse the provider's cached prefix for memory extraction. Subscription traffic uses normal extraction. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). +For a Responses upstream configured without a subscription, prefix extraction is enabled by default; `PC_GATEWAY_PREFIX_EXTRACTION=off` disables it. Capture remains opt-in. Core also needs its gateway callback URL and generation model configured. With that URL configured, the Server defaults to `one_pass` unless a processing mode was explicitly supplied; `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=per_candidate` retains the previous mode. Native subscription prefix extraction remains disabled. One-pass normally caches its own memory-generation conversation, while per-candidate processing can reuse the agent prefix. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). + +## Steering + +Responses requests include the [built-in cost guidance](crates/pc-gateway-app/src/default_steering.txt) by default. Set `PC_GATEWAY_STEERING_FILE` to replace it, or `PC_GATEWAY_STEERING=off` to disable steering even when a file is configured. Chat requests are unchanged. Both `PC_GATEWAY_STEERING` and `PC_GATEWAY_PREFIX_EXTRACTION` accept only `on` or `off` when set. See [instruction settings](../docs/en/docs/operate/deploy-server.md#gateway-instruction). ## Run diff --git a/gateway/crates/pc-gateway-app/src/default_steering.txt b/gateway/crates/pc-gateway-app/src/default_steering.txt new file mode 100644 index 0000000000..da9cc26f99 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/default_steering.txt @@ -0,0 +1 @@ +Cost guidance: every tool call re-sends the whole conversation, so the number of steps dominates cost. Plan before acting: locate the relevant code with one or two targeted searches, read only the line ranges you need and batch independent reads into a single command, then make the complete change in as few edits as possible. Run the most relevant tests once; do not spend many steps repairing the test environment, a targeted compile or import check is acceptable when tests cannot run. diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 39744eb87d..81cfc02ce2 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -68,9 +68,9 @@ pub struct AppState { pub inject_code: bool, /// 过检后同步沉淀对话(默认关)。 pub sediment: bool, - /// 运维配置的固定指令(`PC_GATEWAY_STEERING_FILE`),只插入 Responses 请求;未配置时为空。 + /// 默认内置固定指令,只插入 Responses 请求;文件可覆盖,`PC_GATEWAY_STEERING=off` 可关闭。 pub steering: Option, - /// 为 Core 保留会话前缀以复用缓存抽取记忆:`PC_GATEWAY_PREFIX_EXTRACTION=on`(默认关,#2413)。 + /// 非订阅上游默认保留记忆抽取前缀;`PC_GATEWAY_PREFIX_EXTRACTION=off` 可关闭(#2413)。 pub prefix_extraction: bool, /// 默认 Scope(启动时读一次,避免热路径读环境变量)。 pub default_scope: String, @@ -163,8 +163,20 @@ async fn main() { _ => pc_gateway_core::DegradePolicy::Pause, }; - // 指令文件只在启动时读取;配置了但无效时拒绝启动,而不是不带指令运行。 - let steering = match steering::load(std::env::var("PC_GATEWAY_STEERING_FILE").ok().as_deref()) { + let steering_enabled = default_on("PC_GATEWAY_STEERING").unwrap_or_else(|reason| { + eprintln!("{reason}"); + std::process::exit(2); + }); + let prefix_extraction = default_on("PC_GATEWAY_PREFIX_EXTRACTION").unwrap_or_else(|reason| { + eprintln!("{reason}"); + std::process::exit(2); + }); + // 显式关闭时不读取指令文件;开启时文件优先于内置文本,配置无效则拒绝启动。 + let steering = match if steering_enabled { + steering::load(std::env::var("PC_GATEWAY_STEERING_FILE").ok().as_deref()) + } else { + Ok(None) + } { Ok(steering) => steering, Err(reason) => { tracing::error!("PC_GATEWAY_STEERING_FILE: {reason}"); @@ -292,11 +304,7 @@ async fn main() { ), sediment, steering, - prefix_extraction: subscription_kind.is_none() - && matches!( - std::env::var("PC_GATEWAY_PREFIX_EXTRACTION").as_deref(), - Ok("on") - ), + prefix_extraction: subscription_kind.is_none() && prefix_extraction, default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") .unwrap_or_else(|_| "gateway:default".into()), max_body_bytes: model_body_bytes, @@ -329,6 +337,16 @@ async fn main() { .expect("serve"); } +/// Default-on feature switches reject misspellings instead of silently enabling a feature. +fn default_on(name: &str) -> Result { + match std::env::var(name) { + Ok(value) if value == "on" => Ok(true), + Ok(value) if value == "off" => Ok(false), + Err(std::env::VarError::NotPresent) => Ok(true), + _ => Err(format!("{name} must be on or off")), + } +} + fn subscription_from_env( ) -> Result, pc_gateway_auth::AuthError> { let value = match std::env::var("PC_GATEWAY_SUBSCRIPTION") { diff --git a/gateway/crates/pc-gateway-app/src/steering.rs b/gateway/crates/pc-gateway-app/src/steering.rs index 6efb806307..f016fda898 100644 --- a/gateway/crates/pc-gateway-app/src/steering.rs +++ b/gateway/crates/pc-gateway-app/src/steering.rs @@ -12,10 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! 运维配置的固定指令(`PC_GATEWAY_STEERING_FILE`),只插入 Responses 入口的请求。 +//! 默认内置固定指令,可由 `PC_GATEWAY_STEERING_FILE` 覆盖;只插入 Responses 入口的请求。 //! //! 文本在启动时读取并校验一次;每个请求插入同一位置的同一文本,因此它是稳定前缀的一部分, -//! 首个请求之后按缓存读取计费。它与上下文注入、沉淀和准备结果的重放相互独立。 +//! 可复用上游前缀缓存,实际命中与计费取决于服务商。它与上下文注入、沉淀和准备结果的重放相互独立。 use serde_json::Value; @@ -26,14 +26,16 @@ pub const MAX_STEERING_BYTES: usize = 4096; /// 指令文本含有它时每个请求都会被拒绝,所以启动时就拒绝。 const RESERVED_MARKER_PREFIX: &str = "BEGIN_POWERCONTEXT_"; -/// 读取并校验指令文件:未配置时返回 `None`;文件不可读、不是 UTF-8、去掉首尾空白后为空、超过 +/// 读取并校验固定指令:未配置文件时使用内置文本;文件不可读、不是 UTF-8、去掉首尾空白后为空、超过 /// [`MAX_STEERING_BYTES`] 或含有 PowerContext 保留标记时返回错误,网关据此拒绝启动,而不是不带指令运行。 pub fn load(path: Option<&str>) -> Result, String> { - let Some(path) = path else { - return Ok(None); + let text = match path { + Some(path) => { + let bytes = std::fs::read(path).map_err(|_| "file cannot be read".to_string())?; + String::from_utf8(bytes).map_err(|_| "file is not UTF-8".to_string())? + } + None => include_str!("default_steering.txt").to_owned(), }; - let bytes = std::fs::read(path).map_err(|_| "file cannot be read".to_string())?; - let text = String::from_utf8(bytes).map_err(|_| "file is not UTF-8".to_string())?; let text = text.trim(); if text.is_empty() { return Err("file is empty".into()); @@ -106,7 +108,9 @@ mod tests { std::fs::write(&path, bytes).unwrap(); path.to_string_lossy().into_owned() }; - assert_eq!(load(None), Ok(None)); + let default = load(None).unwrap().unwrap(); + assert!(default.starts_with("Cost guidance:")); + assert!(default.len() <= MAX_STEERING_BYTES); assert_eq!( load(Some(&file("ok", b" Plan before acting.\n"))), Ok(Some("Plan before acting.".into())) diff --git a/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs b/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs index 262b483076..5a073847ce 100644 --- a/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs +++ b/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs @@ -130,6 +130,15 @@ enum Startup { impl Gateway { async fn start(replies: Vec, deny: Option<(&'static str, &'static str)>) -> Self { + // Golden protocol fixtures exercise requests without operator steering. + Self::start_with_env(replies, deny, &[("PC_GATEWAY_STEERING", "off")]).await + } + + async fn start_with_env( + replies: Vec, + deny: Option<(&'static str, &'static str)>, + settings: &[(&str, &str)], + ) -> Self { let peers = Arc::new(Peers { replies: Mutex::new(replies.into()), deny, @@ -200,6 +209,7 @@ impl Gateway { .env("PC_GATEWAY_API_KEY", "gateway-test-key") .env("PC_GATEWAY_INJECTION", "off") .env("PC_GATEWAY_SEDIMENT", "off") + .envs(settings.iter().copied()) // Gateway diagnostics go to stdout/stderr; capture them per attempt and report // them together with the exit status on failure. .stdout(Stdio::from(log_file.try_clone().unwrap())) @@ -773,3 +783,145 @@ async fn responses_stream_delivers_reasoning_summaries_and_citations() { body["stream"] = json!(false); gateway.assert_forwarded(&[body], &[bytes]); } + +#[tokio::test] +async fn default_steering_and_overrides_reach_only_responses() { + let custom = + std::env::temp_dir().join(format!("pc-default-steering-{}.txt", std::process::id())); + std::fs::write(&custom, "Custom deployment guidance.").unwrap(); + let custom_path = custom.to_str().unwrap(); + let missing = custom.with_extension("missing"); + for (settings, expected) in [ + ( + vec![], + Some("Cost guidance: every tool call re-sends the whole conversation"), + ), + ( + vec![("PC_GATEWAY_STEERING_FILE", custom_path)], + Some("Custom deployment guidance."), + ), + (vec![("PC_GATEWAY_STEERING", "off")], None), + ( + vec![ + ("PC_GATEWAY_STEERING", "off"), + ("PC_GATEWAY_STEERING_FILE", missing.to_str().unwrap()), + ], + None, + ), + ] { + let gateway = Gateway::start_with_env( + vec![ + Reply::fixture("fantasy_responses_simple", 0), + Reply::fixture("fantasy_chat_simple", 0), + ], + None, + &settings, + ) + .await; + assert!(gateway + .post("responses", &request("responses", "simple", false)) + .await + .status() + .is_success()); + assert!(gateway + .post("chat/completions", &request("chat", "simple", false)) + .await + .status() + .is_success()); + let sent = gateway.peers.sent.lock().unwrap(); + let responses: Value = serde_json::from_slice(&sent[0].1).unwrap(); + let developer: Vec<_> = responses["input"] + .as_array() + .unwrap() + .iter() + .filter(|message| message["role"] == "developer") + .collect(); + match expected { + Some(text) => { + assert_eq!(developer.len(), 1, "settings: {settings:?}"); + assert!(developer[0]["content"][0]["text"] + .as_str() + .unwrap() + .starts_with(text)); + } + None => assert!(developer.is_empty(), "settings: {settings:?}"), + } + let chat: Value = serde_json::from_slice(&sent[1].1).unwrap(); + assert_eq!(chat["messages"].as_array().unwrap().len(), 2); + assert!(chat["messages"] + .as_array() + .unwrap() + .iter() + .all(|message| message["role"] != "developer")); + } + std::fs::remove_file(custom).unwrap(); +} + +#[tokio::test] +async fn prefix_extraction_defaults_on_but_respects_off_and_subscription_boundary() { + for (settings, expected) in [ + (vec![], "prefix_unavailable"), + ( + vec![("PC_GATEWAY_PREFIX_EXTRACTION", "off")], + "prefix_extraction_disabled", + ), + ( + vec![ + ("PC_GATEWAY_PREFIX_EXTRACTION", "on"), + ("PC_GATEWAY_SUBSCRIPTION", "codex"), + ( + "PC_GATEWAY_SUBSCRIPTION_CREDENTIALS", + "/synthetic/not-read-by-extract.json", + ), + ("PC_GATEWAY_UPSTREAM_URL_CHAT", ""), + ( + "PC_GATEWAY_UPSTREAM_URL_RESPONSES", + "https://chatgpt.com/backend-api/codex/responses", + ), + ], + "prefix_extraction_disabled", + ), + ] { + let gateway = Gateway::start_with_env(vec![], None, &settings).await; + let response = gateway + .post( + "extract", + &json!({"handle": "unknown", "instruction": "Extract memory."}), + ) + .await; + assert_eq!(response.status(), 404); + assert_eq!(response.json::().await.unwrap()["error"], expected); + assert!(gateway.peers.sent.lock().unwrap().is_empty()); + } +} + +#[test] +fn invalid_default_feature_switches_reject_startup() { + for setting in ["PC_GATEWAY_STEERING", "PC_GATEWAY_PREFIX_EXTRACTION"] { + let mut child = Command::new(env!("CARGO_BIN_EXE_pc-gateway")) + .env_clear() + .env("PC_GATEWAY_LISTEN", "127.0.0.1:0") + .env("PC_GATEWAY_CORE_BASE", "http://127.0.0.1:9") + .env(setting, "of") + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(2); + let mut exited = false; + while std::time::Instant::now() < deadline { + if child.try_wait().unwrap().is_some() { + exited = true; + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + if !exited { + child.kill().unwrap(); + } + let result = child.wait_with_output().unwrap(); + assert!(exited, "{setting} accepted an invalid switch"); + assert_eq!(result.status.code(), Some(2)); + assert!(String::from_utf8(result.stderr).unwrap().contains(setting)); + } +} diff --git a/src/powercontext/server/settings.py b/src/powercontext/server/settings.py index 502d9c3f1d..c2f94a6117 100644 --- a/src/powercontext/server/settings.py +++ b/src/powercontext/server/settings.py @@ -279,6 +279,10 @@ def settings_customise_sources( # BaseSettings serializes nested model defaults before validation. Keep an # omitted name implicit so legacy detection and environment selection work. init_settings.init_kwargs["database"] = database.model_dump(exclude={"database"}) + runtime = init_settings.init_kwargs.get("runtime") + if isinstance(runtime, RuntimeConfig) and "atomic_memory_processing_mode" not in runtime.model_fields_set: + # Preserve an omitted mode for environment overrides and the Gateway deployment default. + init_settings.init_kwargs["runtime"] = runtime.model_dump(exclude={"atomic_memory_processing_mode"}) return super().settings_customise_sources( settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings ) @@ -311,6 +315,15 @@ def configure_default_local_skill_targets(self) -> ServerSettings: self.external_skills = _default_local_external_skills(self.workspace) return self + @model_validator(mode="after") + def configure_gateway_memory_processing(self) -> ServerSettings: + if ( + self.inference.prefix_extraction_gateway_url is not None + and "atomic_memory_processing_mode" not in self.runtime.model_fields_set + ): + self.runtime = self.runtime.model_copy(update={"atomic_memory_processing_mode": "one_pass"}) + return self + @field_validator("public_url") @classmethod def validate_public_url(cls, value: str | None) -> str | None: diff --git a/tests/test_server_generation.py b/tests/test_server_generation.py index d76bf7d60b..4df1191906 100644 --- a/tests/test_server_generation.py +++ b/tests/test_server_generation.py @@ -17,7 +17,8 @@ import pytest from pydantic import ValidationError -from powercontext.builtin.runtime import InferenceConfig +from powercontext.builtin.runtime import BuiltinConfig, InferenceConfig, RuntimeConfig +from powercontext.server.settings import ServerSettings def test_generation_model_settings_require_generation_model() -> None: @@ -72,3 +73,81 @@ def test_prefix_extraction_cached_input_ratio_is_a_price_fraction() -> None: with pytest.raises(ValidationError, match="prefix_extraction_cached_input_ratio"): InferenceConfig.model_validate({"prefix_extraction_cached_input_ratio": ratio}) assert InferenceConfig().prefix_extraction_cached_input_ratio == 0.1 + + +@pytest.fixture +def gateway_memory_environment(monkeypatch) -> None: + monkeypatch.setenv("POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL", "provider:model") + monkeypatch.setenv("POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_GATEWAY_URL", "http://127.0.0.1:8787") + + +def test_non_gateway_server_and_sdk_keep_per_candidate_memory_default() -> None: + assert ServerSettings().runtime.atomic_memory_processing_mode == "per_candidate" + inference = InferenceConfig.model_validate({ + "generation_model": "provider:model", + "prefix_extraction_gateway_url": "http://127.0.0.1:8787", + }) + assert BuiltinConfig(inference=inference).runtime.atomic_memory_processing_mode == "per_candidate" + + +@pytest.mark.parametrize("source", ["default", "model", "mapping", "environment"]) +def test_gateway_server_defaults_omitted_memory_mode_to_one_pass( + gateway_memory_environment, monkeypatch, source +) -> None: + original = RuntimeConfig(source_window_limit=7) + if source == "model": + settings = ServerSettings(runtime=original) + elif source == "mapping": + settings = ServerSettings(runtime={"source_window_limit": 7}) # ty: ignore[invalid-argument-type] + else: + if source == "environment": + monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_SOURCE_WINDOW_LIMIT", "7") + settings = ServerSettings() + + assert settings.runtime.atomic_memory_processing_mode == "one_pass" + if source != "default": + assert settings.runtime.source_window_limit == 7 + assert original.atomic_memory_processing_mode == "per_candidate" + assert original.model_fields_set == {"source_window_limit"} + + +@pytest.mark.parametrize("source", ["model", "mapping", "environment"]) +@pytest.mark.parametrize("mode", ["per_candidate", "one_pass"]) +def test_gateway_server_preserves_explicit_memory_mode(gateway_memory_environment, monkeypatch, source, mode) -> None: + if source == "model": + settings = ServerSettings(runtime=RuntimeConfig(atomic_memory_processing_mode=mode)) + elif source == "mapping": + settings = ServerSettings(runtime={"atomic_memory_processing_mode": mode}) # ty: ignore[invalid-argument-type] + else: + monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE", mode) + settings = ServerSettings() + assert settings.runtime.atomic_memory_processing_mode == mode + + +@pytest.mark.parametrize("explicit_mode", [None, "one_pass"]) +def test_gateway_server_merges_runtime_model_with_environment( + gateway_memory_environment, monkeypatch, explicit_mode +) -> None: + monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE", "per_candidate") + monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_SOURCE_WINDOW_LIMIT", "99") + original = ( + RuntimeConfig(source_window_limit=7) + if explicit_mode is None + else RuntimeConfig(source_window_limit=7, atomic_memory_processing_mode=explicit_mode) + ) + + settings = ServerSettings(runtime=original) + + assert settings.runtime.atomic_memory_processing_mode == (explicit_mode or "per_candidate") + assert settings.runtime.source_window_limit == 7 + + +@pytest.mark.parametrize("exclude_unset", [False, True]) +def test_gateway_server_respects_serialized_runtime_memory_mode(gateway_memory_environment, exclude_unset) -> None: + runtime = RuntimeConfig(source_window_limit=7).model_dump(exclude_unset=exclude_unset) + settings = ServerSettings(runtime=runtime) + # A full dump supplies a concrete mode; an unset-only dump still asks for the deployment default. + expected = "one_pass" if exclude_unset else "per_candidate" + assert settings.runtime.atomic_memory_processing_mode == expected + restored = ServerSettings(runtime=settings.runtime.model_dump()) + assert restored.runtime.atomic_memory_processing_mode == expected