Skip to content
197 changes: 194 additions & 3 deletions gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ struct Peers {
replies: Mutex<VecDeque<Reply>>,
sent: Mutex<Vec<(HeaderMap, Bytes)>>,
checks: Mutex<Vec<Value>>,
queries: Mutex<Vec<Value>>,
captures: Mutex<Vec<Value>>,
deny: Option<(&'static str, &'static str)>,
}

Expand Down Expand Up @@ -100,6 +102,24 @@ async fn check(State(peers): State<Arc<Peers>>, Json(request): Json<Value>) -> J
}))
}

const PREPARED_BLOCK: &str = "Recall: température";

async fn prepare(State(peers): State<Arc<Peers>>, Json(request): Json<Value>) -> Json<Value> {
peers.queries.lock().unwrap().push(request["query"].clone());
Json(json!({
"schema": "powercontext.prepared-context-with-reuse.v1",
"context": {"schema": "powercontext.prepared-context.v1", "status": "ready",
"content": PREPARED_BLOCK, "content_bytes": PREPARED_BLOCK.len()},
"reuse": {"schema": "powercontext.context-reuse.v1",
"expires_at": "2999-01-01T00:00:00Z", "binding": "test-reuse"}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve per-preparation responses in the shared fixture

headerless_requests_replay_preparation_within_each_turn still expects reuse-1/reuse-2 bindings and Prepared context 1/Prepared context 2, but this shared handler now returns fixed values, making that existing test fail at its first binding assertion. Preserve distinct preparation responses for that test and configure the reminder tests separately.

CI: View the failed check.

}))
}

async fn capture(State(peers): State<Arc<Peers>>, Json(request): Json<Value>) -> Json<Value> {
peers.captures.lock().unwrap().push(request);
Json(json!({}))
}

struct Gateway {
child: Child,
server: tokio::task::JoinHandle<()>,
Expand Down Expand Up @@ -130,6 +150,14 @@ enum Startup {

impl Gateway {
async fn start(replies: Vec<Reply>, deny: Option<(&'static str, &'static str)>) -> Self {
Self::start_with_memory(replies, deny, false).await
}

async fn start_with_memory(
replies: Vec<Reply>,
deny: Option<(&'static str, &'static str)>,
memory: bool,
) -> Self {
let peers = Arc::new(Peers {
replies: Mutex::new(replies.into()),
deny,
Expand All @@ -139,6 +167,8 @@ impl Gateway {
let peer_base = format!("http://{}", listener.local_addr().unwrap());
let router = Router::new()
.route("/v1/context/check", post(check))
.route("/v1/context/prepare", post(prepare))
.route("/v1/sources/content/batch", post(capture))
// Startup discovery needs the complete v1 capability document; without it the model
// routes stay paused (`input_capacity_unconfirmed`). These cases verify payload and
// streaming semantics, so advertise the same ceiling as Core's v1 parser.
Expand All @@ -151,7 +181,7 @@ impl Gateway {
"reuse_versions": [], "reuse_families": [], "enforcing": true,
"limits": {"payload_bytes": 1_048_576, "binding_bytes": 8192,
"prepared_contexts": 16, "dependencies": 256,
"send_seconds": 60, "correlate_seconds": 300}
"send_seconds": 60, "correlate_seconds": 300, "capture_batch_sources": 128}
}}))
}),
)
Expand Down Expand Up @@ -198,8 +228,8 @@ impl Gateway {
)
.env("PC_GATEWAY_UPSTREAM_API_KEY", "provider-test-key")
.env("PC_GATEWAY_API_KEY", "gateway-test-key")
.env("PC_GATEWAY_INJECTION", "off")
.env("PC_GATEWAY_SEDIMENT", "off")
.env("PC_GATEWAY_INJECTION", if memory { "on" } else { "off" })
.env("PC_GATEWAY_SEDIMENT", if memory { "on" } else { "off" })
// 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()))
Expand Down Expand Up @@ -603,6 +633,167 @@ async fn responses_preserves_tool_continuations_and_stream_arguments() {
}
}

#[tokio::test]
async fn responses_reminders_preserve_recall_and_turn_capture() {
let case = "fantasy_responses_tool";
let replies = vec![
Reply::fixture(case, 0),
Reply::fixture(case, 1),
Reply::fixture(case, 1),
];
let bodies: Vec<_> = replies.iter().map(|reply| reply.body.clone()).collect();
let gateway = Gateway::start_with_memory(replies, None, true).await;
let mut baseline = request("responses", "tool", false);
let prompt = baseline["input"][1]["content"][0]["text"].clone();
let startup = json!({"role": "user", "content": "<system-reminder>Auto mode is active</system-reminder>"});
let reminder = json!({"type": "message", "role": "user", "content": [
{"type": "input_text", "text": " <system-reminder>Repeated tool call</system-reminder>\n"},
{"type": "input_text", "text": "<system-reminder>Update the to-do list</system-reminder> "}
]});
let mut initial = baseline.clone();
initial["input"]
.as_array_mut()
.unwrap()
.push(startup.clone());
let tool_call: Value =
serde_json::from_slice::<Value>(&bodies[0]).unwrap()["output"][0].clone();
let arguments = tool_call["arguments"].clone();
let tool_output = json!({
"type": "function_call_output", "output": "Warm", "call_id": tool_call["call_id"]
});
baseline["input"]
.as_array_mut()
.unwrap()
.extend([tool_call, tool_output]);
let mut continuation = baseline.clone();
continuation["input"]
.as_array_mut()
.unwrap()
.insert(2, startup);
continuation["input"].as_array_mut().unwrap().push(reminder);

let mut expected = Vec::new();
for (body, reply) in [initial, continuation, baseline].into_iter().zip(&bodies) {
let response = gateway
.client
.post(format!("{}/responses", gateway.base))
.bearer_auth("gateway-test-key")
.header("x-powercontext-conversation-id", "reminder-turn")
.json(&body)
.send()
.await
.unwrap();
released_responses(response, reply, false).await;
let mut sent = body;
// Responses renders canonical user messages without the optional item type.
if let Some(item) = sent["input"].get_mut(5) {
item.as_object_mut().unwrap().remove("type");
}
sent["input"][1]["content"][0]["text"] =
json!(format!("{PREPARED_BLOCK}\n\n{}", prompt.as_str().unwrap()));
expected.push(sent);
}

assert_eq!(
gateway.peers.queries.lock().unwrap().as_slice(),
std::slice::from_ref(&prompt)
);
gateway.assert_forwarded(&expected, &bodies);
let checks = gateway.peers.checks.lock().unwrap();
for send in checks.iter().step_by(2) {
let locations = send["prepared_contexts"].as_array().unwrap();
assert_eq!(locations.len(), 1);
assert_eq!(locations[0]["binding"], "test-reuse");
assert_eq!(
locations[0]["location"]["pointer"],
"/input/1/content/0/text"
);
assert_eq!(locations[0]["location"]["start_byte"], 0);
assert_eq!(locations[0]["location"]["end_byte"], PREPARED_BLOCK.len());
}

let captures = gateway.peers.captures.lock().unwrap();
assert_eq!(captures.len(), 2);
assert_eq!(captures[0], captures[1]);
let sources = captures[0]["sources"].as_array().unwrap();
assert_eq!(sources.len(), 1);
let transcript: Value = serde_json::from_str(sources[0]["content"].as_str().unwrap()).unwrap();
assert_eq!(transcript["user"], prompt);
assert_eq!(
transcript["steps"],
json!([
{"type": "tool_call", "name": "weather", "arguments": arguments},
{"type": "tool_output", "output": "Warm"}
])
);
}

#[tokio::test]
async fn chat_reminders_preserve_mixed_user_content() {
let reminder = "<system-reminder>Auto mode is active</system-reminder>";
let prompt = "Explain these tags.";
let unclosed = "<system-reminder> Explain this unclosed tag";
let mixed = json!([
{"type": "text", "text": reminder},
{"type": "text", "text": prompt}
]);
let multimodal = json!([
{"type": "text", "text": reminder},
{"type": "image_url", "image_url": {"url": "https://example.com/image.png"}}
]);
let replies: Vec<_> = (0..4)
.map(|_| Reply::fixture("fantasy_chat_simple", 0))
.collect();
let bodies: Vec<_> = replies.iter().map(|reply| reply.body.clone()).collect();
let gateway = Gateway::start_with_memory(replies, None, true).await;
let mut expected = Vec::new();
for (content, injected) in [
(json!(reminder), json!(reminder)),
(mixed.clone(), {
let mut parts = mixed;
parts[0]["text"] = json!(format!("{PREPARED_BLOCK}\n\n{reminder}"));
parts
}),
(multimodal.clone(), {
let mut parts = multimodal;
parts[0]["text"] = json!(format!("{PREPARED_BLOCK}\n\n{reminder}"));
parts
}),
(
json!(unclosed),
json!(format!("{PREPARED_BLOCK}\n\n{unclosed}")),
),
] {
let mut body = request("chat", "simple", false);
body["messages"][1]["content"] = content;
body["messages"].as_array_mut().unwrap().push(json!({
"role": "user", "content": [{"type": "text", "text": reminder}]
}));
let response = gateway.post("chat/completions", &body).await;
assert_eq!(response.status(), 200);
body["messages"][1]["content"] = injected;
expected.push(body);
}
assert_eq!(
*gateway.peers.queries.lock().unwrap(),
[
json!(format!("{reminder}\n{prompt}")),
json!(reminder),
json!(unclosed)
]
);
gateway.assert_forwarded(&expected, &bodies);
let captures = gateway.peers.captures.lock().unwrap();
assert_eq!(captures.len(), 3);
let transcript: Value =
serde_json::from_str(captures[1]["sources"][0]["content"].as_str().unwrap()).unwrap();
assert_eq!(
transcript["user"],
format!("{reminder}\n[image_url: https://example.com/image.png]")
);
assert_eq!(transcript["steps"], json!([]));
}

#[tokio::test]
async fn responses_preserves_refusals_and_call_identity() {
for streaming in [false, true] {
Expand Down
27 changes: 3 additions & 24 deletions gateway/crates/pc-gateway-core/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use crate::lifecycle::Execution;
use crate::prefix_store::{PrefixEntry, PrefixStore};
use crate::replay_cache::{message_anchor, PreparedBlock, ReplayCache, MAX_REPLAY_MS};
use crate::transcript::turn_transcript;
use crate::turn_message::{is_text_part, last_user_index, text_part};

/// Core 的 before_send 在复用证明的依赖已变化或证明已失效时给出的 withhold 原因。
const CONTEXT_REFRESH_REQUIRED: &str = "context-refresh-required";
Expand Down Expand Up @@ -1201,33 +1202,14 @@ fn classify_gate_error(e: GateError) -> String {
}
}

/// 文本内容部件:Chat 为 `text`,Responses 的用户输入为 `input_text`。
fn is_text_part(part: &serde_json::Value) -> bool {
matches!(
part.get("type").and_then(|t| t.as_str()),
Some("text" | "input_text")
)
}

fn last_user_index(request: &CanonicalRequest) -> Option<usize> {
request
.messages
.iter()
.rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User))
}

fn last_user_text(request: &CanonicalRequest) -> Option<String> {
let i = last_user_index(request)?;
match request.messages[i].content.as_slice() {
[serde_json::Value::String(s)] => Some(s.clone()),
// typed content parts:[{"type":"text"或"input_text","text":"..."},...] → 拼接 text 字段。
// 这是 Chat 与 Responses 的合法形态;不处理会导致沉淀 user 为空 + 注入被跳过。
parts if !parts.is_empty() => {
let texts: Vec<String> = parts
.iter()
.filter(|p| is_text_part(p))
.filter_map(|p| p.get("text").and_then(|t| t.as_str()).map(String::from))
.collect();
let texts: Vec<_> = parts.iter().filter_map(text_part).collect();
if texts.is_empty() {
None
} else {
Expand All @@ -1243,10 +1225,7 @@ fn last_user_text(request: &CanonicalRequest) -> Option<String> {
/// 各自的标识。
fn turn_digest(call: &ManagedCall, pristine: &CanonicalRequest) -> Option<String> {
let conversation = call.conversation_id.as_deref()?;
let last_user = pristine
.messages
.iter()
.rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User))?;
let last_user = last_user_index(pristine)?;
let messages = serde_json::to_string(&pristine.messages[..=last_user]).ok()?;
Some(simple_digest(&format!(
"{}\n{}\n{}\n{messages}",
Expand Down
1 change: 1 addition & 0 deletions gateway/crates/pc-gateway-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ mod lifecycle;
mod prefix_store;
mod replay_cache;
mod transcript;
mod turn_message;
mod uds_gate_client;

pub use executor::*;
Expand Down
6 changes: 2 additions & 4 deletions gateway/crates/pc-gateway-core/src/replay_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
//! 区分工具续写(锚点相同 → 重放同一内容与绑定)和新的用户消息(锚点变化 → 准备一次)。
//! 锚点只在可信会话内比较,不用作会话身份。

use crate::turn_message::last_user_index;
use pc_gateway_protocol::CanonicalRequest;
use std::collections::hash_map::DefaultHasher;
use std::collections::VecDeque;
Expand Down Expand Up @@ -54,10 +55,7 @@ pub(crate) struct ReplayCache {

/// 消息锚点:截至最后一条用户消息(含)的原始消息摘要;没有用户消息时为 `None`。
pub(crate) fn message_anchor(request: &CanonicalRequest) -> Option<u64> {
let last_user = request
.messages
.iter()
.rposition(|m| matches!(m.role, pc_gateway_protocol::Role::User))?;
let last_user = last_user_index(request)?;
let prefix = serde_json::to_string(&request.messages[..=last_user]).ok()?;
let mut hasher = DefaultHasher::new();
prefix.hash(&mut hasher);
Expand Down
12 changes: 6 additions & 6 deletions gateway/crates/pc-gateway-core/src/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@

//! 一个用户回合的规范化记录,供网关在回合结束时沉淀。
//!
//! 回合从最后一条用户消息开始,到不再调用工具的响应(终止响应)结束。记录完整保留这一回合里模型读到的内容:
//! 回合从最后一条非独立宿主提醒的用户消息开始,到不再调用工具的响应(终止响应)结束。记录保留这一回合里的:
//! 用户文本、其后的其他消息、工具调用的全部参数字段、工具输出与错误、推理的可见摘要、无法识别的条目,以及助手
//! 文本;字段不截断,步骤不省略。只有推理密文、各类 ID、状态、用量等传输元数据不进入记录,二进制数据(截图、
//! 文本;字段不截断,步骤不省略。独立的宿主提醒、推理密文、各类 ID、状态、用量等传输元数据不进入记录,二进制数据(截图、
//! 图片、文件)记为带字节数的占位文本。用户文本取自注入前的请求,不含准备结果。
//!
//! 一段 Source 的估算规模不超过 Core 生效的 Atomic Memory 输入上限,也不超过 [`MAX_SOURCE_TOKENS`];超过时记录
//! 按顺序拆成几段,每段都是独立的 Source。

use crate::capture_coverage::declaration;
use crate::turn_message::last_user_index;
use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, Role};
use serde::Serialize;
use serde_json::{Map, Value};
Expand Down Expand Up @@ -121,13 +122,12 @@ pub(crate) fn turn_transcript(
} else {
(Vec::new(), chat_final_text(&response)?)
};
let start = request
.messages
.iter()
.rposition(|m| matches!(m.role, Role::User))?;
let start = last_user_index(request)?;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Align prefix extraction with the selected prompt

When prefix extraction processes a captured Responses request ending in a standalone reminder, the Source now starts at the earlier prompt, but the retained prefix includes the reminder and prefixed_extraction.py::PREFIX_EVIDENCE_NOTE still selects the last user message as evidence. Both extraction modes are therefore instructed to exclude captured prompt/tool evidence and include the omitted reminder; carry the selected boundary into prefix extraction or fall back to normal extraction for these turns.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for flagging this. I pushed ff51d5b. When a trailing reminder makes the raw last-user boundary differ from the selected prompt, the Gateway now omits the prefix handle and Core uses the normal captured Source. The provider request is unchanged, and turns with matching boundaries still use prefix extraction. The Responses regression now runs with prefix extraction enabled and checks both paths, including the original prompt and tool output. All 146 targeted Gateway tests passed locally.

let user = parts_text(&request.messages[start].content);
let mut steps: Vec<Step> = request.messages[start + 1..]
.iter()
// Any user messages after the selected prompt are standalone reminders.
.filter(|m| m.role != Role::User)
.flat_map(|m| {
if is_responses(list_key) {
m.content.iter().flat_map(item_steps).collect()
Expand Down
Loading