diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs index e8e348c..dc23322 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-native-client.rs @@ -393,7 +393,15 @@ fn invoke( } transport.poll_resends()?; } - bail!("Ghostlight native operation timed out") + let stats = transport.stats(); + bail!( + "Ghostlight native operation timed out while connected={}; transport sent {} bytes/{} frames and received {} bytes/{} frames", + transport.connected(), + stats.bytes_sent, + stats.frames_sent, + stats.bytes_received, + stats.frames_received, + ) } fn operation_timeout(operation: &str) -> Duration { diff --git a/crates/ghostlight-dungeon/src/native_cultmesh.rs b/crates/ghostlight-dungeon/src/native_cultmesh.rs index 4245497..647bea8 100644 --- a/crates/ghostlight-dungeon/src/native_cultmesh.rs +++ b/crates/ghostlight-dungeon/src/native_cultmesh.rs @@ -121,13 +121,33 @@ fn run_server( loop { while let Ok(completed) = completed_rx.try_recv() { in_flight.fetch_sub(1, Ordering::SeqCst); - if hub - .session(completed.session.remote_addr) - .is_some_and(|active| { - active.session_generation == completed.session.session_generation - }) - { - hub.send_schema_message(&completed.session, &completed.response)?; + let (message_id, payload_bytes) = response_diagnostics(&completed.response); + match hub.session(completed.session.remote_addr) { + Some(active) + if active.session_generation == completed.session.session_generation => + { + tracing::info!( + %message_id, + payload_bytes, + session_generation = completed.session.session_generation, + remote_addr = %completed.session.remote_addr, + "Ghostlight native boundary delivered completed operation response" + ); + hub.send_schema_message(&completed.session, &completed.response)?; + } + Some(active) => tracing::warn!( + %message_id, + completed_session_generation = completed.session.session_generation, + active_session_generation = active.session_generation, + remote_addr = %completed.session.remote_addr, + "Ghostlight native boundary fenced a completed response from a replaced session" + ), + None => tracing::warn!( + %message_id, + session_generation = completed.session.session_generation, + remote_addr = %completed.session.remote_addr, + "Ghostlight native boundary could not deliver a completed response because its session vanished" + ), } } if let Some(event) = hub.receive_event_once()? { @@ -171,6 +191,17 @@ fn run_server( } } +fn response_diagnostics(response: &CultNetMessage) -> (String, usize) { + match response { + CultNetMessage::OperationResponse { + message_id, + payload, + .. + } => (message_id.clone(), payload.len()), + _ => ("non-operation-response".into(), 0), + } +} + pub(super) async fn handle_operation(state: AppState, request: CultNetMessage) -> CultNetMessage { match handle_operation_inner(state, &request).await { Ok(response) => response, diff --git a/crates/ghostlight-dungeon/src/outcome.rs b/crates/ghostlight-dungeon/src/outcome.rs index 6623ec0..0f289df 100644 --- a/crates/ghostlight-dungeon/src/outcome.rs +++ b/crates/ghostlight-dungeon/src/outcome.rs @@ -16,7 +16,7 @@ use std::{ }; use tokio::{sync::Semaphore, task::JoinSet}; -const OUTCOME_PROPOSAL_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named outcomes—never action_resolutions, results, or resolutions. outcomes is an array with one item per supplied action_digest. Every item requires action_digest, band (success, mixed, or failure), effect_kind, and supporting_state_references. Fields are conditionally required, not optional suggestions: no_material_change requires reason; resource_created and resource_consumed require owner_subject_id and resource; resource_transferred requires owner_subject_id, other_subject_id, and resource; gestalt_pressure requires owner_subject_id plus both pressure arrays; agency_relation_shift requires relation_id and strength_delta; member_memory requires member_id and memory; member_obligation requires member_id and obligation; member_relationship requires member_id, other_subject_id, and relationship_description; knowledge_learned requires owner_subject_id and fact_id. Every scalar field not named for the chosen effect_kind is omitted or null; irrelevant pressure arrays are omitted or empty. A non-neutral irrelevant field is invalid. pressure_additions and pressure_resolutions are arrays of plain strings, never objects. no_material_change uses an empty supporting_state_references array; every material effect cites the smallest causally decisive set of one to eight values copied literally and only from that action's allowed_state_references. A source_subject_id, target_subject_id, target_state subject_id, member_state_owner_id, owner_subject_id, other_subject_id, member_id, relation_id, or fact_id is not a supporting state reference unless that exact string also appears in allowed_state_references. For member_relationship, other_subject_id already identifies the target; do not repeat it as provenance. Do not emit summary; Ghostlight derives it from the validated typed effect. When resource_created is admissible and concrete capability-backed making or repair establishes a durable source-owned result, the resource field names that resulting object, stock, repair, or usable arrangement. It never restates an action or an unnamed recipient's response. Example no-op shape: {"outcomes":[{"action_digest":"sha256:","band":"mixed","effect_kind":"no_material_change","supporting_state_references":[],"reason":"No durable state changed."}]}"#; +const OUTCOME_PROPOSAL_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named outcomes—never action_resolutions, results, or resolutions. outcomes is an array with one item per supplied action_digest. Every item requires action_digest, band (success, mixed, or failure), effect_kind, and supporting_state_references. Fields are conditionally required, not optional suggestions: no_material_change requires reason; resource_created and resource_consumed require owner_subject_id and resource; resource_transferred requires owner_subject_id, other_subject_id, and resource; gestalt_pressure requires owner_subject_id plus both pressure arrays; agency_relation_shift requires relation_id and strength_delta; member_memory requires member_id and memory; member_obligation requires member_id and obligation; member_relationship requires member_id, other_subject_id, and relationship_description; knowledge_learned requires owner_subject_id and fact_id. Every scalar field not named for the chosen effect_kind is omitted or null; irrelevant pressure arrays are omitted, null, or empty and normalize to empty before semantic binding. A non-neutral irrelevant field is invalid. For gestalt_pressure, pressure_additions and pressure_resolutions must be arrays of plain strings, never null or objects. no_material_change uses an empty supporting_state_references array; every material effect cites the smallest causally decisive set of one to eight values copied literally and only from that action's allowed_state_references. A source_subject_id, target_subject_id, target_state subject_id, member_state_owner_id, owner_subject_id, other_subject_id, member_id, relation_id, or fact_id is not a supporting state reference unless that exact string also appears in allowed_state_references. For member_relationship, other_subject_id already identifies the target; do not repeat it as provenance. Do not emit summary; Ghostlight derives it from the validated typed effect. When resource_created is admissible and concrete capability-backed making or repair establishes a durable source-owned result, the resource field names that resulting object, stock, repair, or usable arrangement. It never restates an action or an unnamed recipient's response. Example no-op shape: {"outcomes":[{"action_digest":"sha256:","band":"mixed","effect_kind":"no_material_change","supporting_state_references":[],"reason":"No durable state changed."}]}"#; const OUTCOME_VERIFIER_OUTPUT_CONTRACT: &str = r#"The top-level object has exactly one field named verdicts—never verifications, outcomes, results, or resolutions. verdicts is an array with one item per supplied action_digest. Every item has exactly action_digest, result, and repair_guidance. Example: {"verdicts":[{"action_digest":"sha256:","result":"match","repair_guidance":null}]}"#; #[derive(Clone, Debug, Serialize)] @@ -93,9 +93,9 @@ struct OutcomeProposal { strength_delta: Option, #[serde(default)] resource: Option, - #[serde(default)] + #[serde(default, deserialize_with = "null_as_empty_vec")] pressure_additions: Vec, - #[serde(default)] + #[serde(default, deserialize_with = "null_as_empty_vec")] pressure_resolutions: Vec, #[serde(default)] member_id: Option, @@ -111,6 +111,13 @@ struct OutcomeProposal { reason: Option, } +fn null_as_empty_vec<'de, D>(deserializer: D) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok(Option::>::deserialize(deserializer)?.unwrap_or_default()) +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] struct OutcomeVerifierBundle { @@ -1674,6 +1681,12 @@ fn constrain_outcome_schema( let proposal = schema .pointer_mut("/$defs/OutcomeProposal") .ok_or_else(|| anyhow!("strategic outcome schema has no proposal definition"))?; + for field in ["pressure_additions", "pressure_resolutions"] { + let array_schema = proposal["properties"][field].take(); + proposal["properties"][field] = serde_json::json!({ + "anyOf":[array_schema,{"type":"null"}] + }); + } proposal["required"] = serde_json::json!([ "action_digest", "band", @@ -1784,7 +1797,7 @@ fn outcome_effect_shape( if matches!(*field, "pressure_additions" | "pressure_resolutions") { serde_json::json!({ "required":[field], - "properties":{(*field):{"minItems":1}} + "properties":{(*field):{"type":"array","minItems":1}} }) } else { serde_json::json!({ @@ -1807,11 +1820,13 @@ fn outcome_effect_shape( }, "required":required }); - for field in required_effect_fields - .iter() - .filter(|field| !matches!(**field, "pressure_additions" | "pressure_resolutions")) - { - shape["properties"][*field] = serde_json::json!({"not":{"type":"null"}}); + for field in required_effect_fields.iter() { + shape["properties"][*field] = + if matches!(*field, "pressure_additions" | "pressure_resolutions") { + serde_json::json!({"type":"array"}) + } else { + serde_json::json!({"not":{"type":"null"}}) + }; } if !forbidden.is_empty() { shape["not"] = serde_json::json!({"anyOf":forbidden}); @@ -2713,6 +2728,22 @@ mod tests { "reason":"No durable state changes." }] }))); + let nullable_inactive_arrays = serde_json::json!({ + "outcomes":[{ + "action_digest":digest, + "band":"mixed", + "effect_kind":"no_material_change", + "supporting_state_references":[], + "pressure_additions":null, + "pressure_resolutions":null, + "reason":"No durable state changes." + }] + }); + assert!(validator.is_valid(&nullable_inactive_arrays)); + let normalized: OutcomeProposalBundle = + serde_json::from_value(nullable_inactive_arrays).unwrap(); + assert!(normalized.outcomes[0].pressure_additions.is_empty()); + assert!(normalized.outcomes[0].pressure_resolutions.is_empty()); assert!(!validator.is_valid(&outcome(None, None))); assert!(!validator.is_valid(&outcome(Some("invented-owner"), None))); assert!(!validator.is_valid(&outcome( @@ -2791,6 +2822,17 @@ mod tests { assert!(validator.is_valid(&pressure(vec!["crew exhaustion"], vec![]))); assert!(validator.is_valid(&pressure(vec![], vec!["storm damage"]))); assert!(!validator.is_valid(&pressure(vec![], vec![]))); + assert!(!validator.is_valid(&serde_json::json!({ + "outcomes":[{ + "action_digest":context.action_digest, + "band":"mixed", + "effect_kind":"gestalt_pressure", + "supporting_state_references":["pressure:dockers:storm damage"], + "owner_subject_id":"dockers", + "pressure_additions":null, + "pressure_resolutions":["storm damage"] + }] + }))); let repeated_pressure = pressure(vec!["storm damage"], vec![]); assert!(validator.is_valid(&repeated_pressure)); let repeated_bundle: OutcomeProposalBundle = diff --git a/vendor/cultnet-rs/tests/rudp_server_hub.rs b/vendor/cultnet-rs/tests/rudp_server_hub.rs index a8a2c11..7533959 100644 --- a/vendor/cultnet-rs/tests/rudp_server_hub.rs +++ b/vendor/cultnet-rs/tests/rudp_server_hub.rs @@ -166,6 +166,52 @@ fn hub_keeps_independent_peer_sessions_and_exposes_connect_evidence() -> Result< Ok(()) } +#[test] +fn hub_delivers_a_large_response_after_a_long_keepalive_only_operation() -> Result<()> { + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut options = CultNetRudpServerHubOptions::new("ghostlight", server_socket, CONNECTION_ID); + options.max_fragment_bytes = Some(2_048); + options.max_pending_reliable_packets = Some(4_096); + let mut hub = CultNetRudpServerHub::new(options)?; + let mut player = client(server_addr)?; + let session = connect(&mut hub, &mut player, b"long-operation-session")?; + + for heartbeat in 0..64_u32 { + player.ping(heartbeat.to_be_bytes().to_vec())?; + assert!(hub.receive_event_once()?.is_none()); + assert!(player.receive_once()?.is_none()); + } + assert_eq!(hub.session(session.remote_addr), Some(&session)); + + let payload = "x".repeat(256_000); + let response = CultNetMessage::OperationResponse { + message_id: "long-operation".into(), + service_id: "ghostlight.native.player".into(), + operation: "ghostlight.eve.invoke".into(), + status: "accepted".into(), + payload_schema: "gamecult.eve.command_result.v1".into(), + payload_encoding: "messagepack-base64".into(), + payload: payload.clone(), + diagnostics: vec![], + source_runtime_id: Some("ghostlight".into()), + target_runtime_id: Some("player".into()), + }; + hub.send_schema_message(&session, &response)?; + + let mut received = None; + for _ in 0..2_000 { + if let Some(message) = player.receive_schema_message_once()? { + received = Some(message); + break; + } + let _ = hub.receive_event_once()?; + hub.poll_resends()?; + } + assert_eq!(received, Some(response)); + Ok(()) +} + #[test] fn hub_fences_replaced_generations_and_does_not_replace_connect_retransmits() -> Result<()> { let server_socket = socket()?;