Class: R::NewBridgeAdapter
- Inherits:
-
Object
- Object
- R::NewBridgeAdapter
- Includes:
- Singleton
- Defined in:
- lib/R_interface/new_bridge_adapter.rb
Overview
Phase 5.1 adapter: expose a minimal compatibility surface for legacy call sites that historically depended on ShadowBridge (now deprecated/obsolete). backed by NewBridge::SessionClient.
Implemented compatibility methods:
- eval_r(code)
- eval_r_with_result("g2_v_x <- ...")
- ready?
- in_callback?
- close
Instance Method Summary collapse
-
#assign_session(session_id, key, value_expr) ⇒ Object
Assign value expression into session environment.
-
#batch_eval_r_with_result(assignment_codes) ⇒ Array<Hash>
Multiple eval_r_with_result-style assignments in one REQ/RET (Phase 4).
- #close ⇒ Object
-
#dispatch_probe(handle, name) ⇒ Object
Single round-trip replacement for the two eval_r probes in R::Support.process_missing_dispatch (is_field + is_func).
- #effective_bridge_timeout(timeout: nil) ⇒ Object
-
#ensure_session_env(session_id = current_session_id) ⇒ Object
Ensure session-scoped environment exists and return its R env handle.
-
#eval_r(code, timeout: nil) ⇒ Object
Minimal textual compatibility for existing call sites that expect "[1]
" style output for simple scalar evaluations. -
#eval_r_async(code, timeout: nil, &block) ⇒ Object
Async string eval:
blockreceivesNewBridge::EvalResult; on success#valueis the same formatted string aseval_r(no phase1 scalar fallback retry on async path). -
#eval_r_with_result(assignment_code) ⇒ Object
Legacy-compatible envelope shape expected by existing bridge specs.
-
#eval_r_with_result_async(assignment_code, timeout: nil, &block) ⇒ Object
Async
eval_r_with_resultpayload;blockreceivesNewBridge::EvalResultwhere success#valueis a Hash:envelope,:var_name,:r_exprforR::Support.ruby_result_from_envelope. -
#get_session(session_id, key) ⇒ Object
Get a value from session environment (parsed payload).
- #in_callback? ⇒ Boolean
-
#initialize ⇒ NewBridgeAdapter
constructor
A new instance of NewBridgeAdapter.
-
#print_r(var_name) ⇒ Object
Return the printed representation of an R object as a Ruby string.
-
#pull_dataframe(var_name) ⇒ Object
data.frame unboxing: Ruby hash { "colname" => [values...] }.
- #pull_double_vector(var_name, _total_size, offset = 0, chunk_size = nil) ⇒ Object
-
#pull_integer_vector(var_name, _total_size, offset = 0, chunk_size = nil) ⇒ Object
Indexed vector unboxing helpers expected by R::Vector#unboxed_get.
-
#pull_vector(var_name) ⇒ Object
Unbox atomic vectors to Ruby Arrays.
-
#push_double_vector(ruby_array, var_name, offset = nil, _total_size = nil) ⇒ Object
Push Ruby numeric array values into an R numeric vector.
- #ready? ⇒ Boolean
-
#register_callback_proc_stub(proc_or_method) ⇒ Object
Phase 5.3 callback stub registration for R::Support.parse_arg.
-
#rm_session(session_id, key) ⇒ Object
Remove a key from session environment.
- #unbox_list_element(var_name, one_based_index) ⇒ Object
-
#unbox_list_length(var_name) ⇒ Object
Structural unboxing helpers (Phase 5.5 hardening): Keep deep unboxing on explicit bridge reads instead of generic method-missing paths.
-
#unbox_materialize(var_name, max_depth:, max_nodes:) ⇒ Object
Specialized one-call materialization for nested list/scalar/null trees.
-
#unbox_walk(var_name, max_depth:, max_nodes:) ⇒ Object
Specialized bounded traversal for deep unboxing checks.
-
#with_session(session_id) ⇒ Object
Execute bridge operations within a specific NewBridge session_id.
Constructor Details
#initialize ⇒ NewBridgeAdapter
Returns a new instance of NewBridgeAdapter.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 20 def initialize @in_callback = false @ready = false source_path = ENV['GALAAZ_NEW_BRIDGE_SOURCE'] || File.('../../ext/new_bridge/galaaz_gatekeeper_phase1.cpp', __dir__) @client = NewBridge::SessionClient.new(source_path: source_path) @client.start(accept_timeout: 120) # Compatibility with the legacy ShadowBridge setup: # - `R.awt` / X11 for plotting (examples/sthda_ggplot). # - `missing_arg()` for Ruby :all in `[` / tbl subset (R::Support.parse_arg). # Use rlang::missing_arg when available: tibble/tidyselect reject the legacy # quote(f(,0))[[2]] sentinel ("Subscript ... can't contain the empty string"). # The gatekeeper evaluates each REQ in a dedicated per-session env; globals are shared. init_timeout = effective_bridge_timeout(timeout: nil) @client.eval_r( <<~RCODE, ({ assign('awt', function(...) { X11(...) }, envir = .GlobalEnv) if (requireNamespace('rlang', quietly = TRUE)) { assign('missing_arg', getExportedValue('rlang', 'missing_arg'), envir = .GlobalEnv) } else { assign('missing_arg', function() { quote(f(,0))[[2]] }, envir = .GlobalEnv) } # Build tidyselect-compatible range expressions from symbols, e.g. year:day. if (!exists('range_helper', envir = .GlobalEnv, inherits = FALSE)) { assign('range_helper', function(col_ini, col_end, remove = FALSE) { ini <- substitute(col_ini) fin <- substitute(col_end) rng <- as.call(list(as.name(':'), ini, fin)) if (isTRUE(remove)) { as.call(list(as.name('-'), rng)) } else { rng } }, envir = .GlobalEnv) } if (!exists('up_to', envir = .GlobalEnv, inherits = FALSE)) { assign('up_to', function(col_ini, col_end, remove = FALSE) { range_helper(col_ini, col_end, remove = remove) }, envir = .GlobalEnv) } # Legacy Galaaz: env_names(env) lists bindings (base R has no env_names). if (!exists('env_names', envir = .GlobalEnv, inherits = FALSE)) { assign('env_names', function(envir) { if (missing(envir)) envir <- parent.frame() ls(envir = envir, all.names = TRUE, sorted = TRUE) }, envir = .GlobalEnv) } # Session-scoped environment helpers for transient bridge state. if (!exists('galaaz_ensure_session_env', envir = .GlobalEnv, inherits = FALSE)) { assign('galaaz_ensure_session_env', function(session_id) { sid <- as.character(session_id) # Primary path: reuse gatekeeper's per-session registry. if (exists('.galaaz_sessions', envir = .GlobalEnv, inherits = FALSE)) { sessions <- get('.galaaz_sessions', envir = .GlobalEnv, inherits = FALSE) if (!is.list(sessions)) { sessions <- list() } if (is.null(sessions[[sid]])) { sessions[[sid]] <- new.env(parent = .GlobalEnv) assign('.galaaz_sessions', sessions, envir = .GlobalEnv) } return(sessions[[sid]]) } # Compatibility fallback if gatekeeper registry is unavailable. nm <- paste0('galaaz_session_env_', gsub('[^A-Za-z0-9_]', '_', sid)) if (!exists(nm, envir = .GlobalEnv, inherits = FALSE)) { assign(nm, new.env(parent = .GlobalEnv), envir = .GlobalEnv) } get(nm, envir = .GlobalEnv, inherits = FALSE) }, envir = .GlobalEnv) } if (!exists('galaaz_assign_session', envir = .GlobalEnv, inherits = FALSE)) { assign('galaaz_assign_session', function(session_id, key, value) { en <- galaaz_ensure_session_env(session_id) assign(as.character(key), value, envir = en) invisible(NULL) }, envir = .GlobalEnv) } if (!exists('galaaz_get_session', envir = .GlobalEnv, inherits = FALSE)) { assign('galaaz_get_session', function(session_id, key) { en <- galaaz_ensure_session_env(session_id) get(as.character(key), envir = en, inherits = FALSE) }, envir = .GlobalEnv) } if (!exists('galaaz_rm_session', envir = .GlobalEnv, inherits = FALSE)) { assign('galaaz_rm_session', function(session_id, key) { en <- galaaz_ensure_session_env(session_id) rm(list = as.character(key), envir = en, inherits = FALSE) invisible(NULL) }, envir = .GlobalEnv) } 0L }) RCODE session_id: current_session_id, parent_id: callback_parent_id, timeout: init_timeout ) @ready = true end |
Instance Method Details
#assign_session(session_id, key, value_expr) ⇒ Object
Assign value expression into session environment. value_expr must be a valid R expression string.
281 282 283 284 285 286 287 288 289 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 281 def assign_session(session_id, key, value_expr) sid = session_id.to_s k = key.to_s @client.eval_r("({ galaaz_assign_session(#{sid.inspect}, #{k.inspect}, { #{value_expr} }); 0L })", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) nil end |
#batch_eval_r_with_result(assignment_codes) ⇒ Array<Hash>
Multiple eval_r_with_result-style assignments in one REQ/RET (Phase 4). Fail-fast: first R error
skips remaining ops. Transport still returns HTTP-like success with payload kind batch_error.
242 243 244 245 246 247 248 249 250 251 252 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 242 def batch_eval_r_with_result(assignment_codes) codes = Array(assignment_codes).map(&:to_s) raise ArgumentError, 'batch_eval_r_with_result requires at least one assignment' if codes.empty? body = codes.join("\u001E") parsed = @client.eval_r("__G_BATCH_EVAL_WITH_RESULT__#{body}", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) decode_batch_eval_payload(parsed) end |
#close ⇒ Object
404 405 406 407 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 404 def close @client&.stop @ready = false end |
#dispatch_probe(handle, name) ⇒ Object
Single round-trip replacement for the two eval_r probes in R::Support.process_missing_dispatch (is_field + is_func). Gatekeeper: G_DISPATCH_PROBE|handle|name
257 258 259 260 261 262 263 264 265 266 267 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 257 def dispatch_probe(handle, name) parsed = @client.eval_r("__G_DISPATCH_PROBE__|#{handle}|#{name}", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) unless parsed['kind'].to_s == 'dispatch_probe' raise "dispatch_probe: unexpected payload #{parsed.inspect}" end { is_field: parsed['is_field'], is_func: parsed['is_func'] } end |
#effective_bridge_timeout(timeout: nil) ⇒ Object
312 313 314 315 316 317 318 319 320 321 322 323 324 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 312 def effective_bridge_timeout(timeout: nil) return timeout if timeout raw = ENV['GALAAZ_BRIDGE_TIMEOUT_SEC'] return 60 if raw.nil? s = raw.to_s.strip return 60 if s.empty? Integer(s) rescue StandardError, ArgumentError 60 end |
#ensure_session_env(session_id = current_session_id) ⇒ Object
Ensure session-scoped environment exists and return its R env handle.
270 271 272 273 274 275 276 277 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 270 def ensure_session_env(session_id = current_session_id) sid = session_id.to_s @client.eval_r("({ galaaz_ensure_session_env(#{sid.inspect}); 0L })", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) nil end |
#eval_r(code, timeout: nil) ⇒ Object
Minimal textual compatibility for existing call sites that expect
"[1]
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 143 def eval_r(code, timeout: nil) effective_timeout = effective_bridge_timeout(timeout: timeout) if ENV['GALAAZ_TIMEOUT_DEBUG'] STDERR.puts "[TIMEOUT_DEBUG] NewBridgeAdapter.eval_r timeout=#{effective_timeout}s explicit_timeout=#{timeout.inspect} env_bridge=#{ENV['GALAAZ_BRIDGE_TIMEOUT_SEC'].inspect}" STDERR.flush end out = @client.eval_r(code, session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_timeout) format_scalar_print(out) rescue NewBridge::SessionClient::RProcessError => e # Compatibility fallback for side-effect-only evals: # only retry when the error clearly matches phase1 scalar restrictions. raise unless phase1_scalar_fallback_error?(e) @client.eval_r("({ #{code}; 0L })", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_timeout) '' end |
#eval_r_async(code, timeout: nil, &block) ⇒ Object
Async string eval: block receives NewBridge::EvalResult; on success #value is the same
formatted string as eval_r (no phase1 scalar fallback retry on async path).
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 164 def eval_r_async(code, timeout: nil, &block) raise ArgumentError, 'eval_r_async requires a block' unless block @client.eval_r_async(code.to_s, session_id: current_session_id, parent_id: callback_parent_id, timeout: timeout) do |raw| mapped = if raw.ok? begin NewBridge::EvalResult.success(format_scalar_print(raw.value)) rescue StandardError => e NewBridge::EvalResult.failure(e) end else raw end block.call(mapped) end end |
#eval_r_with_result(assignment_code) ⇒ Object
Legacy-compatible envelope shape expected by existing bridge specs. Supports scalar assignments used by current migration subset.
230 231 232 233 234 235 236 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 230 def eval_r_with_result(assignment_code) parsed = @client.eval_r("__G_EVAL_WITH_RESULT__#{assignment_code}", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) to_legacy_envelope(parsed) end |
#eval_r_with_result_async(assignment_code, timeout: nil, &block) ⇒ Object
Async eval_r_with_result payload; block receives NewBridge::EvalResult where success #value
is a Hash :envelope, :var_name, :r_expr for R::Support.ruby_result_from_envelope.
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 187 def eval_r_with_result_async(assignment_code, timeout: nil, &block) raise ArgumentError, 'eval_r_with_result_async requires a block' unless block code = "__G_EVAL_WITH_RESULT__#{assignment_code}" @client.eval_r_async(code, session_id: current_session_id, parent_id: callback_parent_id, timeout: timeout) do |raw| if raw.ok? begin env = to_legacy_envelope(raw.value) m = assignment_code.match(/\A(\S+)\s*<-\s*(.*)\z/m) unless m block.call(NewBridge::EvalResult.failure(StandardError.new("eval_r_with_result_async: bad assignment #{assignment_code.inspect}"))) next end vn = m[1] rx = m[2].to_s.strip block.call(NewBridge::EvalResult.success(envelope: env, var_name: vn, r_expr: rx)) rescue StandardError => e block.call(NewBridge::EvalResult.failure(e)) end else block.call(raw) end end end |
#get_session(session_id, key) ⇒ Object
Get a value from session environment (parsed payload).
292 293 294 295 296 297 298 299 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 292 def get_session(session_id, key) sid = session_id.to_s k = key.to_s @client.eval_r("galaaz_get_session(#{sid.inspect}, #{k.inspect})", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) end |
#in_callback? ⇒ Boolean
127 128 129 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 127 def in_callback? @in_callback end |
#print_r(var_name) ⇒ Object
Return the printed representation of an R object as a Ruby string.
216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 216 def print_r(var_name) parsed = @client.eval_r("paste(capture.output(print(#{var_name})), collapse='\\n')", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) if parsed['kind'].to_s == 'character' unescape_scalar_character(parsed['value'].to_s) else parsed['value'].to_s end end |
#pull_dataframe(var_name) ⇒ Object
data.frame unboxing: Ruby hash { "colname" => [values...] }.
Column-wise bulk path: assign each column to a temp g2_v* handle, then
pull_vector (uses __G_PULL_VECTOR__ when supported). Per-cell scalar
evals are avoided for atomic columns; list / unsupported columns still
fall back inside pull_vector.
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 557 def pull_dataframe(var_name) t = effective_bridge_timeout(timeout: nil) sid = current_session_id pid = callback_parent_id ncol = @client.eval_r("length(#{var_name})", session_id: sid, parent_id: pid, timeout: t)['value'].to_i return {} if ncol <= 0 col_hash = {} (1..ncol).each do |i| col_name_parsed = @client.eval_r("names(#{var_name})[#{i}]", session_id: sid, parent_id: pid, timeout: t) col_name = col_name_parsed['value'] col_name = col_name.to_s if col_name tmp = ::R::Support.generate_var_name @client.eval_r("({ #{tmp} <- #{var_name}[[#{i}]]; 0L })", session_id: sid, parent_id: pid, timeout: t) col_hash[col_name] = pull_vector(tmp) end col_hash end |
#pull_double_vector(var_name, _total_size, offset = 0, chunk_size = nil) ⇒ Object
501 502 503 504 505 506 507 508 509 510 511 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 501 def pull_double_vector(var_name, _total_size, offset = 0, chunk_size = nil) chunk_size ||= 1 start_1 = offset + 1 begin raw = eval_pull_vector_payload(var_name, slice_start_1based: start_1, slice_count: chunk_size) out = decode_pull_vector_bulk_payload(raw, want_kind: 'double_vector') return out if out.is_a?(Array) && out.size == chunk_size rescue NewBridge::SessionClient::RProcessError end pull_double_vector_elementwise(var_name, offset, chunk_size) end |
#pull_integer_vector(var_name, _total_size, offset = 0, chunk_size = nil) ⇒ Object
Indexed vector unboxing helpers expected by R::Vector#unboxed_get. offset is 0-based (Ruby index), R indexing is 1-based.
489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 489 def pull_integer_vector(var_name, _total_size, offset = 0, chunk_size = nil) chunk_size ||= 1 start_1 = offset + 1 begin raw = eval_pull_vector_payload(var_name, slice_start_1based: start_1, slice_count: chunk_size) out = decode_pull_vector_bulk_payload(raw, want_kind: 'integer_vector') return out if out.is_a?(Array) && out.size == chunk_size rescue NewBridge::SessionClient::RProcessError end pull_integer_vector_elementwise(var_name, offset, chunk_size) end |
#pull_vector(var_name) ⇒ Object
Unbox atomic vectors to Ruby Arrays.
Primary path: gatekeeper __G_PULL_VECTOR__ (one round-trip for full vector).
Fallback: per-element scalar eval (complex types, older gatekeeper, errors).
476 477 478 479 480 481 482 483 484 485 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 476 def pull_vector(var_name) begin raw = eval_pull_vector_payload(var_name) out = decode_pull_vector_bulk_payload(raw) return out unless out.nil? rescue NewBridge::SessionClient::RProcessError # Unsupported SEXP type, unknown handle, or legacy binary without pull_vector. end pull_vector_elementwise(var_name) end |
#push_double_vector(ruby_array, var_name, offset = nil, _total_size = nil) ⇒ Object
Push Ruby numeric array values into an R numeric vector.
- ruby_array: Ruby Array of Numeric/nil (nil mapped to NA_real_)
- var_name: target R variable handle/name
- offset/total_size: when provided, writes a slice using 0-based offset
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 517 def push_double_vector(ruby_array, var_name, offset = nil, _total_size = nil) values = Array(ruby_array) return nil if values.empty? serialized = values.map do |v| if v.nil? 'NA_real_' elsif v.is_a?(Numeric) v.finite? ? v.to_f.to_s : 'NA_real_' else begin Float(v).to_s rescue StandardError 'NA_real_' end end end.join(', ') if offset start_i = offset.to_i + 1 end_i = offset.to_i + values.length @client.eval_r("({ #{var_name}[#{start_i}:#{end_i}] <- c(#{serialized}); 0L })", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) else @client.eval_r("({ #{var_name} <- c(#{serialized}); 0L })", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) end nil end |
#ready? ⇒ Boolean
123 124 125 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 123 def ready? @ready end |
#register_callback_proc_stub(proc_or_method) ⇒ Object
Phase 5.3 callback stub registration for R::Support.parse_arg. Returns an R function string that forwards callback execution to Ruby using the NewBridge CALL/RET path.
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 329 def register_callback_proc_stub(proc_or_method) callback_session_id = current_session_id callback_wait_ms = begin raw = ENV.fetch('GALAAZ_CALLBACK_TIMEOUT_MS', '120000').to_s.strip v = Integer(raw) v > 0 ? v : 120_000 rescue StandardError 120_000 end if ENV['GALAAZ_TIMEOUT_DEBUG'] STDERR.puts "[TIMEOUT_DEBUG] NewBridgeAdapter.register_callback_proc_stub callback_wait_ms=#{callback_wait_ms} env_callback=#{ENV['GALAAZ_CALLBACK_TIMEOUT_MS'].inspect}" STDERR.flush end # Stable R-safe fragment for namespacing callback result keys (session + call id). sess_key = callback_session_id.to_s.gsub(/[^a-zA-Z0-9_]/, '_') callback_call_id = @client.register_callback do |payload, call_id| old = Thread.current[:galaaz_new_bridge_parent_id] old_session = Thread.current[:galaaz_new_bridge_session_id] Thread.current[:galaaz_new_bridge_parent_id] = call_id Thread.current[:galaaz_new_bridge_session_id] = callback_session_id @in_callback = true begin cb_args = callback_payload_to_r_objects(payload) # Legacy arity-2 procs (phase 5.3 specs): (first R arg or nil, Ruby CALL envelope id). # Knitr/RubyCallback use arity != 2 and receive call(*cb_args). ar = proc_or_method.respond_to?(:arity) ? proc_or_method.arity : 0 raw = if ar == 2 && cb_args.size <= 1 proc_or_method.call(cb_args[0], call_id) else proc_or_method.call(*cb_args) end # Semantic return value: store in session env. # Transport RET is ACK-only (SessionClient sends "1"); R stub reads env after CALL/RET. slot_key = "r_#{sess_key}_#{call_id.gsub('-', '_')}" rhs = raw.is_a?(String) ? raw : R::Support.parse_arg(raw) assign_session(callback_session_id, slot_key, rhs) # Semantic value is staged in session env; RET must be ACK-only (nil → transport "1"). nil ensure @in_callback = false Thread.current[:galaaz_new_bridge_session_id] = old_session Thread.current[:galaaz_new_bridge_parent_id] = old end end # Each ... arg is assigned in session env under a temporary handle. # Names must be g2_v + digits # only — gatekeeper valid_bridge_handle_token rejects g2_v_cb_* (letters after g2_v), which # breaks dispatch_probe when Ruby wraps the handle as R::Object. "function(...) { args <- list(...) handles <- character(0) if (length(args) > 0L) { for (i in seq_along(args)) { h <- paste0('g2_v', as.integer(stats::runif(1, 1e7, 9e7 - 1L)), sprintf('%04d', as.integer(i))) galaaz_assign_session('#{callback_session_id}', h, args[[i]]) cls <- paste(class(args[[i]]), collapse = ' ') handles <- c(handles, paste0(h, ':', cls)) } } payload <- paste(handles, collapse = '|') gid <- '#{callback_call_id}' galaaz_callback_call_phase3(gid, payload, #{callback_wait_ms}) sess <- '#{sess_key}' nm <- paste0('r_', sess, '_', gsub('-', '_', gid)) sid <- '#{callback_session_id}' if (exists(nm, envir = galaaz_ensure_session_env(sid), inherits = FALSE)) { val <- galaaz_get_session(sid, nm) galaaz_rm_session(sid, nm) return(val) } stop('callback staged no semantic value in session env') }" end |
#rm_session(session_id, key) ⇒ Object
Remove a key from session environment.
302 303 304 305 306 307 308 309 310 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 302 def rm_session(session_id, key) sid = session_id.to_s k = key.to_s @client.eval_r("({ galaaz_rm_session(#{sid.inspect}, #{k.inspect}); 0L })", session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) nil end |
#unbox_list_element(var_name, one_based_index) ⇒ Object
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 416 def unbox_list_element(var_name, one_based_index) tmp = ::R::Support.generate_var_name probe = probe_node_expr("#{var_name}[[#{one_based_index}]]", assign_to: tmp) case probe[:kind] when 'null' nil when 'list' ::R::Object.build(tmp, nil, r_class: 'list') when 'scalar_integer' probe[:value] when 'scalar_double' probe[:value] when 'scalar_logical' probe[:value] when 'scalar_character' v = probe[:value] (v.is_a?(::String) && v =~ /^rb_obj_\d+$/) ? ::R::Support.get_ruby_object(v) : v else r_class = probe[:r_class].to_s.strip return nil if r_class == 'NULL' ::R::Object.build(tmp, nil, r_class: r_class.empty? ? 'unknown' : r_class) end end |
#unbox_list_length(var_name) ⇒ Object
Structural unboxing helpers (Phase 5.5 hardening): Keep deep unboxing on explicit bridge reads instead of generic method-missing paths.
411 412 413 414 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 411 def unbox_list_length(var_name) probe = probe_node_expr(var_name) probe[:length].to_i end |
#unbox_materialize(var_name, max_depth:, max_nodes:) ⇒ Object
Specialized one-call materialization for nested list/scalar/null trees. Returns:
{ status: :ok|:depth_limit|:node_limit|:unsupported, nodes:, max_depth:, value: }
460 461 462 463 464 465 466 467 468 469 470 471 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 460 def unbox_materialize(var_name, max_depth:, max_nodes:) cmd = "__G_UNBOX_MATERIALIZE__|#{var_name}|#{max_depth.to_i}|#{max_nodes.to_i}" parsed = @client.eval_r(cmd, session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) status = case parsed['status'].to_s when 'DEPTH' then :depth_limit when 'NODE' then :node_limit when 'UNSUPPORTED' then :unsupported else :ok end { status: status, nodes: parsed['nodes'].to_i, max_depth: parsed['max_depth'].to_i, value: parsed['value'] } end |
#unbox_walk(var_name, max_depth:, max_nodes:) ⇒ Object
Specialized bounded traversal for deep unboxing checks. Walks nested list structures in one bridge call and reports whether limits were exceeded. Returns:
{ status: :ok|:depth_limit|:node_limit, nodes: Integer, max_depth: Integer }
445 446 447 448 449 450 451 452 453 454 455 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 445 def unbox_walk(var_name, max_depth:, max_nodes:) cmd = "__G_UNBOX_WALK__|#{var_name}|#{max_depth.to_i}|#{max_nodes.to_i}" parsed = @client.eval_r(cmd, session_id: current_session_id, parent_id: callback_parent_id, timeout: effective_bridge_timeout(timeout: nil)) status = case parsed['status'].to_s when 'DEPTH' then :depth_limit when 'NODE' then :node_limit else :ok end { status: status, nodes: parsed['nodes'].to_i, max_depth: parsed['max_depth'].to_i } end |
#with_session(session_id) ⇒ Object
Execute bridge operations within a specific NewBridge session_id. Scope is thread-local and restored after block execution.
133 134 135 136 137 138 139 |
# File 'lib/R_interface/new_bridge_adapter.rb', line 133 def with_session(session_id) old = Thread.current[:galaaz_new_bridge_session_id] Thread.current[:galaaz_new_bridge_session_id] = session_id.to_s yield ensure Thread.current[:galaaz_new_bridge_session_id] = old end |