🚨 Critical Issue #76: SocketBox Method Call Deadlock Investigation

## 🎯 Problem Identification Complete
- SocketBox method calls (bind, isServer, toString) cause infinite blocking
- Root cause: Method resolution pipeline deadlock before execute_socket_method
- Other Box types (ArrayBox, StringBox, MapBox) work normally
- Arc<Mutex> reference sharing confirmed working (Arc addresses match = true)

## 🔧 Debug Infrastructure Added
- Comprehensive debug logging in socket_box.rs (bind, isServer, clone, toString)
- Method call tracing in http_methods.rs
- Deadlock detection points identified at interpreter expressions.rs:462-464

## 📋 Issue #76 Created for Copilot Investigation
- Systematic root cause analysis requirements (Architecture→Parser→Runtime levels)
- Comprehensive test cases: minimal/comprehensive/comparison scenarios
- Strict prohibition of band-aid fixes - architectural analysis required
- Hypothesis: Multiple Arc<Mutex> combinations causing circular deadlock

## 🧪 Test Suite Added
- test_socket_deadlock_minimal.nyash: Minimal reproduction case
- test_socket_methods_comprehensive.nyash: All methods deadlock verification
- test_other_boxes_working.nyash: Normal Box operation confirmation
- SOCKETBOX_ISSUE_REPRODUCTION.md: Complete reproduction guide

## 📊 Impact Assessment
- Phase 9 HTTP server implementation completely blocked
- SocketBox functionality entirely non-functional
- Critical blocker for production readiness
- Requires immediate systematic investigation

🔥 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-08-14 20:55:33 +09:00
parent 7ceaae957a
commit 80c911d3c8
63 changed files with 7720 additions and 75 deletions

View File

@ -56,15 +56,33 @@ pub struct SocketBox {
impl Clone for SocketBox {
fn clone(&self) -> Self {
// 🔧 FIX: Share state containers for "Everything is Box" reference sharing
// This ensures that clones of the same SocketBox share mutable state
Self {
eprintln!("🔥 SOCKETBOX CLONE DEBUG:");
eprintln!("🔥 Original Socket ID = {}", self.base.id);
eprintln!("🔥 Original Arc pointer = {:p}", &self.is_server);
eprintln!("🔥 Arc strong_count BEFORE = {}", std::sync::Arc::strong_count(&self.is_server));
let cloned = Self {
base: BoxBase::new(), // New unique ID for clone (for debugging/identity)
listener: Arc::clone(&self.listener), // Share the same listener
stream: Arc::clone(&self.stream), // Share the same stream
is_server: Arc::clone(&self.is_server), // 🔧 Share the same state container
is_connected: Arc::clone(&self.is_connected), // 🔧 Share the same state container
};
eprintln!("🔥 Cloned Socket ID = {}", cloned.base.id);
eprintln!("🔥 Cloned Arc pointer = {:p}", &cloned.is_server);
eprintln!("🔥 Arc strong_count AFTER = {}", std::sync::Arc::strong_count(&self.is_server));
eprintln!("🔥 Arc addresses match = {}",
std::ptr::eq(&*self.is_server as *const _, &*cloned.is_server as *const _));
// 状態共有テスト
if let (Ok(orig_guard), Ok(clone_guard)) = (self.is_server.lock(), cloned.is_server.lock()) {
eprintln!("🔥 Original state = {}", *orig_guard);
eprintln!("🔥 Cloned state = {}", *clone_guard);
eprintln!("🔥 States match = {}", *orig_guard == *clone_guard);
}
cloned
}
}
@ -86,28 +104,69 @@ impl SocketBox {
let socket_addr = format!("{}:{}", addr_str, port_str);
eprintln!("🔥 SOCKETBOX DEBUG: bind() called");
eprintln!("🔥 Socket ID = {}", self.base.id);
eprintln!("🔥 Address = {}", socket_addr);
eprintln!("🔥 Arc pointer = {:p}", &self.is_server);
match TcpListener::bind(&socket_addr) {
Ok(listener) => {
eprintln!("✅ TCP bind successful");
// listener設定
match self.listener.lock() {
Ok(mut listener_guard) => {
*listener_guard = Some(listener);
eprintln!("✅ Listener stored successfully");
},
Err(_) => {
Err(e) => {
eprintln!("❌ Failed to lock listener mutex: {}", e);
return Box::new(BoolBox::new(false));
}
}
// is_server状態設定 - 徹底デバッグ
match self.is_server.lock() {
Ok(mut is_server_guard) => {
eprintln!("🔥 BEFORE MUTATION:");
eprintln!("🔥 is_server value = {}", *is_server_guard);
eprintln!("🔥 Arc strong_count = {}", std::sync::Arc::strong_count(&self.is_server));
eprintln!("🔥 Arc weak_count = {}", std::sync::Arc::weak_count(&self.is_server));
eprintln!("🔥 Guard pointer = {:p}", &*is_server_guard);
// 状態変更
*is_server_guard = true;
eprintln!("🔥 AFTER MUTATION:");
eprintln!("🔥 is_server value = {}", *is_server_guard);
eprintln!("🔥 Value confirmed = {}", *is_server_guard == true);
// 明示的にドロップしてロック解除
drop(is_server_guard);
eprintln!("✅ is_server guard dropped");
// 再確認テスト
match self.is_server.lock() {
Ok(check_guard) => {
eprintln!("🔥 RECHECK AFTER DROP:");
eprintln!("🔥 is_server value = {}", *check_guard);
},
Err(e) => {
eprintln!("❌ Failed to recheck: {}", e);
}
}
},
Err(_) => {
// Non-critical error, continue
Err(e) => {
eprintln!("❌ SOCKETBOX: Failed to lock is_server mutex: {}", e);
return Box::new(BoolBox::new(false));
}
}
eprintln!("✅ bind() completed successfully");
Box::new(BoolBox::new(true))
},
Err(_e) => {
// Port might be in use, return false
Err(e) => {
eprintln!("❌ TCP bind failed: {}", e);
Box::new(BoolBox::new(false))
}
}
@ -316,8 +375,27 @@ impl SocketBox {
/// サーバーモード確認
pub fn is_server(&self) -> Box<dyn NyashBox> {
let is_server_value = *self.is_server.lock().unwrap();
Box::new(BoolBox::new(is_server_value))
eprintln!("🔥 SOCKETBOX DEBUG: is_server() called");
eprintln!("🔥 Socket ID = {}", self.base.id);
eprintln!("🔥 Arc pointer = {:p}", &self.is_server);
match self.is_server.lock() {
Ok(is_server_guard) => {
let is_server_value = *is_server_guard;
eprintln!("🔥 IS_SERVER READ:");
eprintln!("🔥 is_server value = {}", is_server_value);
eprintln!("🔥 Arc strong_count = {}", std::sync::Arc::strong_count(&self.is_server));
eprintln!("🔥 Arc weak_count = {}", std::sync::Arc::weak_count(&self.is_server));
eprintln!("🔥 Guard pointer = {:p}", &*is_server_guard);
eprintln!("🔥 Returning BoolBox with value = {}", is_server_value);
Box::new(BoolBox::new(is_server_value))
},
Err(e) => {
eprintln!("❌ SOCKETBOX: Failed to lock is_server mutex in is_server(): {}", e);
Box::new(BoolBox::new(false))
}
}
}
}
@ -327,8 +405,30 @@ impl NyashBox for SocketBox {
}
fn to_string_box(&self) -> StringBox {
let is_server = *self.is_server.lock().unwrap();
let is_connected = *self.is_connected.lock().unwrap();
eprintln!("🔥 SOCKETBOX to_string_box() called - Socket ID = {}", self.base.id);
eprintln!("🔥 Arc pointer = {:p}", &self.is_server);
let is_server = match self.is_server.lock() {
Ok(guard) => {
eprintln!("✅ is_server.lock() successful");
*guard
},
Err(e) => {
eprintln!("❌ is_server.lock() failed: {}", e);
false // デフォルト値
}
};
let is_connected = match self.is_connected.lock() {
Ok(guard) => {
eprintln!("✅ is_connected.lock() successful");
*guard
},
Err(e) => {
eprintln!("❌ is_connected.lock() failed: {}", e);
false // デフォルト値
}
};
let status = if is_server {
"Server"
@ -364,8 +464,23 @@ impl BoxCore for SocketBox {
}
fn fmt_box(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let is_server = *self.is_server.lock().unwrap();
let is_connected = *self.is_connected.lock().unwrap();
eprintln!("🔥 SOCKETBOX fmt_box() called - Socket ID = {}", self.base.id);
let is_server = match self.is_server.lock() {
Ok(guard) => *guard,
Err(e) => {
eprintln!("❌ fmt_box: is_server.lock() failed: {}", e);
false
}
};
let is_connected = match self.is_connected.lock() {
Ok(guard) => *guard,
Err(e) => {
eprintln!("❌ fmt_box: is_connected.lock() failed: {}", e);
false
}
};
let status = if is_server {
"Server"

View File

@ -78,7 +78,7 @@ impl InstanceBox {
// フィールドをVoidBoxで初期化
let mut field_map = HashMap::new();
for field in &fields {
field_map.insert(field.clone(), Box::new(VoidBox::new()) as Box<dyn NyashBox>);
field_map.insert(field.clone(), Arc::new(VoidBox::new()) as Arc<dyn NyashBox>);
}
// Weak fields をHashSetに変換高速判定用
@ -131,7 +131,7 @@ impl InstanceBox {
if let Ok(legacy_box) = value.to_box() {
// Convert Arc<Mutex<dyn NyashBox>> to Box<dyn NyashBox>
if let Ok(inner_box) = legacy_box.try_lock() {
self.fields.lock().unwrap().insert(field_name, inner_box.clone_box());
self.fields.lock().unwrap().insert(field_name, Arc::from(inner_box.clone_box()));
}
}
}

View File

@ -669,7 +669,7 @@ impl NyashInterpreter {
};
// 🌍 this変数をバインドしてstatic初期化実行me構文のため
self.declare_local_variable("me", static_instance);
self.declare_local_variable("me", (*static_instance).clone_box());
for stmt in init_statements {
self.execute_statement(stmt)?;
@ -722,7 +722,7 @@ impl NyashInterpreter {
// GlobalBoxのfieldsに直接挿入
{
let mut fields = global_box.fields.lock().unwrap();
fields.insert("statics".to_string(), Box::new(statics_box));
fields.insert("statics".to_string(), Arc::new(statics_box));
}
eprintln!("🌍 statics namespace created in GlobalBox successfully");
@ -751,7 +751,7 @@ impl NyashInterpreter {
// statics InstanceBoxのfieldsに直接挿入動的フィールド追加
{
let mut fields = statics_instance.fields.lock().unwrap();
fields.insert(name.to_string(), Box::new(instance));
fields.insert(name.to_string(), Arc::new(instance));
}
eprintln!("🔥 Static box '{}' instance registered in statics namespace", name);

View File

@ -10,8 +10,9 @@ use super::*;
use crate::ast::UnaryOperator;
use crate::boxes::{buffer::BufferBox, JSONBox, HttpClientBox, StreamBox, RegexBox, IntentBox, SocketBox, HTTPServerBox, HTTPRequestBox, HTTPResponseBox};
use crate::boxes::{FloatBox, MathBox, ConsoleBox, TimeBox, DateTimeBox, RandomBox, SoundBox, DebugBox, file::FileBox, MapBox};
use crate::box_trait::BoolBox;
use crate::box_trait::{BoolBox, SharedNyashBox};
use crate::operator_traits::OperatorResolver;
use std::sync::Arc;
// TODO: Fix NullBox import issue later
// use crate::NullBox;
@ -65,7 +66,7 @@ impl NyashInterpreter {
.map_err(|_| RuntimeError::InvalidOperation {
message: "'this' is only available inside methods".to_string(),
})?;
Ok((**shared_this).clone_box()) // Convert for external interface
Ok((*shared_this).clone_box()) // Convert for external interface
}
ASTNode::Me { .. } => {
@ -76,7 +77,7 @@ impl NyashInterpreter {
message: "'me' is only available inside methods".to_string(),
})?;
Ok((**shared_me).clone_box()) // Convert for external interface
Ok((*shared_me).clone_box()) // Convert for external interface
}
ASTNode::ThisField { field, .. } => {
@ -86,12 +87,12 @@ impl NyashInterpreter {
message: "'this' is not bound in the current context".to_string(),
})?;
if let Some(instance) = (**this_value).as_any().downcast_ref::<InstanceBox>() {
if let Some(instance) = (*this_value).as_any().downcast_ref::<InstanceBox>() {
let shared_field = instance.get_field(field)
.ok_or_else(|| RuntimeError::InvalidOperation {
message: format!("Field '{}' not found on this", field)
})?;
Ok((**shared_field).clone_box()) // Convert for external interface
Ok((*shared_field).clone_box()) // Convert for external interface
} else {
Err(RuntimeError::TypeError {
message: "'this' is not an instance".to_string(),
@ -106,12 +107,12 @@ impl NyashInterpreter {
message: "'this' is not bound in the current context".to_string(),
})?;
if let Some(instance) = (**me_value).as_any().downcast_ref::<InstanceBox>() {
if let Some(instance) = (*me_value).as_any().downcast_ref::<InstanceBox>() {
let shared_field = instance.get_field(field)
.ok_or_else(|| RuntimeError::InvalidOperation {
message: format!("Field '{}' not found on me", field)
})?;
Ok((**shared_field).clone_box()) // Convert for external interface
Ok((*shared_field).clone_box()) // Convert for external interface
} else {
Err(RuntimeError::TypeError {
message: "'this' is not an instance".to_string(),
@ -464,14 +465,30 @@ impl NyashInterpreter {
// 🔧 FIX: Update stored variable for stateful SocketBox methods
// These methods modify the SocketBox internal state, so we need to update
// the stored local variable to ensure subsequent accesses get the updated state
// the stored variable/field to ensure subsequent accesses get the updated state
if matches!(method, "bind" | "connect" | "close") {
if let ASTNode::Variable { name, .. } = object {
if let Some(stored_var) = self.local_vars.get_mut(name) {
// Replace the stored instance with the modified one
let updated_instance = socket_box.clone();
*stored_var = Box::new(updated_instance);
}
let updated_instance = socket_box.clone();
match object {
ASTNode::Variable { name, .. } => {
// Handle local variables
if let Some(stored_var) = self.local_vars.get_mut(name) {
*stored_var = Arc::new(updated_instance);
}
},
ASTNode::FieldAccess { object: field_obj, field, .. } => {
// Handle StaticBox fields like me.server
if let ASTNode::Variable { name, .. } = field_obj.as_ref() {
if name == "me" {
if let Ok(me_instance) = self.resolve_variable("me") {
if let Some(instance) = (*me_instance).as_any().downcast_ref::<InstanceBox>() {
let _ = instance.set_field(field, Arc::new(updated_instance));
}
}
}
}
},
_ => {}
}
}
@ -554,7 +571,7 @@ impl NyashInterpreter {
if name == "me" {
// Get current instance to check if field is weak
if let Ok(current_me) = self.resolve_variable("me") {
if let Some(current_instance) = (**current_me).as_any().downcast_ref::<InstanceBox>() {
if let Some(current_instance) = (*current_me).as_any().downcast_ref::<InstanceBox>() {
if current_instance.is_weak_field(field) {
return Err(RuntimeError::InvalidOperation {
message: format!(
@ -682,7 +699,8 @@ impl NyashInterpreter {
if let ASTNode::Variable { name, .. } = object {
// Static boxの可能性をチェック
if self.is_static_box(name) {
return self.execute_static_field_access(name, field);
let static_result = self.execute_static_field_access(name, field)?;
return Ok(Arc::from(static_result));
}
}
@ -721,14 +739,14 @@ impl NyashInterpreter {
crate::value::NyashValue::Null => {
eprintln!("🔗 DEBUG: Weak field '{}' is null (reference dropped)", field);
// Return null box for compatibility
return Ok(Box::new(crate::boxes::null_box::NullBox::new()));
return Ok(Arc::new(crate::boxes::null_box::NullBox::new()));
}
_ => {
eprintln!("🔗 DEBUG: Weak field '{}' still has valid reference", field);
// Convert back to Box<dyn NyashBox> for now
if let Ok(box_value) = weak_value.to_box() {
if let Ok(inner_box) = box_value.try_lock() {
return Ok(inner_box.clone_box());
return Ok(Arc::from(inner_box.clone_box()));
}
}
}
@ -782,10 +800,13 @@ impl NyashInterpreter {
})?;
// 3. フィールドアクセス
instance.get_field(field)
let shared_field = instance.get_field(field)
.ok_or(RuntimeError::InvalidOperation {
message: format!("Field '{}' not found in static box '{}'", field, static_box_name),
})
})?;
// Convert Arc to Box for compatibility
Ok((*shared_field).clone_box())
}
@ -865,7 +886,7 @@ impl NyashInterpreter {
message: "'from' can only be used inside methods".to_string(),
})?;
let current_instance = (**current_instance_val).as_any().downcast_ref::<InstanceBox>()
let current_instance = (*current_instance_val).as_any().downcast_ref::<InstanceBox>()
.ok_or(RuntimeError::TypeError {
message: "'from' requires current instance to be InstanceBox".to_string(),
})?;

View File

@ -17,15 +17,25 @@ impl NyashInterpreter {
) -> Result<Box<dyn NyashBox>, RuntimeError> {
match method {
"bind" => {
eprintln!("🔥 SOCKET_METHOD: bind() called");
if arguments.len() != 2 {
return Err(RuntimeError::InvalidOperation {
message: format!("bind() expects 2 arguments, got {}", arguments.len()),
});
}
eprintln!("🔥 SOCKET_METHOD: Evaluating address argument...");
let address = self.execute_expression(&arguments[0])?;
eprintln!("🔥 SOCKET_METHOD: Address evaluated: {}", address.to_string_box().value);
eprintln!("🔥 SOCKET_METHOD: Evaluating port argument...");
let port = self.execute_expression(&arguments[1])?;
Ok(socket_box.bind(address, port))
eprintln!("🔥 SOCKET_METHOD: Port evaluated: {}", port.to_string_box().value);
eprintln!("🔥 SOCKET_METHOD: Calling socket_box.bind()...");
let result = socket_box.bind(address, port);
eprintln!("🔥 SOCKET_METHOD: bind() completed");
Ok(result)
}
"listen" => {
if arguments.len() != 1 {

View File

@ -9,6 +9,7 @@
use super::*;
use crate::boxes::{NullBox, ConsoleBox, FloatBox, DateTimeBox, SocketBox, HTTPServerBox, HTTPRequestBox, HTTPResponseBox};
// use crate::boxes::intent_box_wrapper::IntentBoxWrapper;
use crate::box_trait::SharedNyashBox;
use std::sync::Arc;
impl NyashInterpreter {
@ -708,6 +709,9 @@ impl NyashInterpreter {
// 現在のスコープでBoxを追跡自動解放のため
// 🌍 革命的実装Environment tracking廃止
// Create Arc outside if block so it's available in all scopes
let instance_arc = Arc::from(instance_box);
// コンストラクタを呼び出す
// "pack/引数数"、"init/引数数"、"Box名/引数数" の順で試す
let pack_key = format!("pack/{}", arguments.len());
@ -718,7 +722,6 @@ impl NyashInterpreter {
.or_else(|| final_box_decl.constructors.get(&init_key))
.or_else(|| final_box_decl.constructors.get(&box_name_key)) {
// コンストラクタを実行
let instance_arc = Arc::from(instance_box);
self.execute_constructor(&instance_arc, constructor, arguments, &final_box_decl)?;
} else if !arguments.is_empty() {
return Err(RuntimeError::InvalidOperation {

View File

@ -298,13 +298,13 @@ impl NyashInterpreter {
// 既存のフィールド値があればfini()を呼ぶ
if let Some(old_field_value) = instance.get_field(field) {
if let Some(old_instance) = old_field_value.as_any().downcast_ref::<InstanceBox>() {
if let Some(old_instance) = (*old_field_value).as_any().downcast_ref::<InstanceBox>() {
let _ = old_instance.fini();
finalization::mark_as_finalized(old_instance.box_id());
}
}
instance.set_field(field, val.clone_box())
instance.set_field(field, Arc::from(val.clone_box()))
.map_err(|e| RuntimeError::InvalidOperation { message: e })?;
Ok(val)
} else {
@ -321,7 +321,7 @@ impl NyashInterpreter {
message: "'this' is not bound in the current context".to_string(),
})?;
if let Some(instance) = (**this_value).as_any().downcast_ref::<InstanceBox>() {
if let Some(instance) = (*this_value).as_any().downcast_ref::<InstanceBox>() {
// 🔥 Usage prohibition guard - check if instance is finalized
if instance.is_finalized() {
return Err(RuntimeError::InvalidOperation {
@ -331,13 +331,13 @@ impl NyashInterpreter {
// 既存のthis.field値があればfini()を呼ぶ
if let Some(old_field_value) = instance.get_field(field) {
if let Some(old_instance) = old_field_value.as_any().downcast_ref::<InstanceBox>() {
if let Some(old_instance) = (*old_field_value).as_any().downcast_ref::<InstanceBox>() {
let _ = old_instance.fini();
finalization::mark_as_finalized(old_instance.box_id());
}
}
instance.set_field(field, val.clone_box())
instance.set_field(field, Arc::from(val.clone_box()))
.map_err(|e| RuntimeError::InvalidOperation { message: e })?;
Ok(val)
} else {
@ -354,7 +354,7 @@ impl NyashInterpreter {
message: "'this' is not bound in the current context".to_string(),
})?;
if let Some(instance) = (**me_value).as_any().downcast_ref::<InstanceBox>() {
if let Some(instance) = (*me_value).as_any().downcast_ref::<InstanceBox>() {
// 🔥 Usage prohibition guard - check if instance is finalized
if instance.is_finalized() {
return Err(RuntimeError::InvalidOperation {
@ -364,13 +364,13 @@ impl NyashInterpreter {
// 既存のme.field値があればfini()を呼ぶ
if let Some(old_field_value) = instance.get_field(field) {
if let Some(old_instance) = old_field_value.as_any().downcast_ref::<InstanceBox>() {
if let Some(old_instance) = (*old_field_value).as_any().downcast_ref::<InstanceBox>() {
let _ = old_instance.fini();
finalization::mark_as_finalized(old_instance.box_id());
}
}
instance.set_field(field, val.clone_box())
instance.set_field(field, Arc::from(val.clone_box()))
.map_err(|e| RuntimeError::InvalidOperation { message: e })?;
Ok(val)
} else {

View File

@ -201,7 +201,7 @@ impl EphemeralInstance {
let inst = parent.lock().unwrap();
if let Some(instance_box) = inst.as_any().downcast_ref::<InstanceBox>() {
if let Some(field_value) = instance_box.get_field(name) {
return Some(field_value);
return Some((*field_value).clone_box());
}
}
}