1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
open Ast

(*
--# Unified Data Retrieval (get)
--#
--# Retrieves values from environments, collections, or pipelines using names, 
--# indices, or lenses. 
--#
--# This is a polymorphic primitive that unifies several retrieval modes:
--#
--# 1. **Variable Lookup**: `get("var_name")` retrieves a variable from the environment.
--# 2. **Collection Indexing**: `get(collection, index)` retrieves an element (0-based).
--# 3. **Pipeline Access**: `get(pipeline, "node_name")` retrieves a specific node result.
--# 4. **Lens Focus**: `get(data, lens)` applies a Lens to focus on a subset of data.
--# 5. **Default Value (Fallback)**: `get(value, default)` returns `value` unchanged when it is not NA/Error; returns `default` when `value` is NA or an Error.
--# 6. **Safe Retrieval**: `get(target, selector, default)` performs the retrieval and returns `default` only when the result is NA (missing key/node or out-of-bounds index). Type errors in unsupported target/selector combinations propagate as errors.
--# 7. **Cross-Node Access (Sandbox)**: `get(node_lens("name"))` retrieves a sibling node's artifact.
--#
--# @name get
--# @param target :: Any The environment name, Collection, Pipeline, Data, or Value to check.
--# @param selector :: Any (Optional) The index, Node name, Lens, or Default value.
--# @param default :: Any (Optional) The default value if the retrieval fails.
--# @return :: Any The retrieved value or the default fallback.
--# @example
--#   salary = 50000
--#   get("salary")                -- 50000 (Lookup)
--#
--#   lst = [10, 20, 30]
--#   get(lst, 1)                  -- 20 (Indexing)
--#
--#   -- Safe indexing with default:
--#   get(lst, 5, 0)               -- 0 (Index out of bounds fallback)
--#
--#   -- Guardrail pattern (any non-NA/Error value is returned as-is):
--#   s = [min_age: NA]
--#   get(s.min_age, 0) >= 0       -- true (NA falls back to 0)
--#   get(42, 0)                   -- 42 (non-NA/Error value returned unchanged)
--#
--#   p = pipeline { a = 1 }
--#   get(p, "a")                  -- 1 (Pipeline Access)
--#   get(p, "missing", "N/A")     -- "N/A" (Safe Pipeline Access)
--#
--#   l = col_lens("mpg")
--#   get(mtcars, l)               -- Vector of 'mpg' column (Lens)
--#
--#   -- Sandbox access (within a Nix-built node):
--#   get(node_lens("node_a"))      -- Deserializes T_NODE_node_a artifact
--#
--# @family core
--# @export
*)
let register ~eval_call env =
  (* Returns the retrieved artifact value or a structured VError if
     sandbox-backed lookup fails. *)
  let get_node_from_env name =
    let env_name = "T_NODE_" ^ name in
    match Sys.getenv_opt env_name with
    | Some path ->
        let artifact_path = Filename.concat path "artifact" in
        if Sys.file_exists artifact_path then
          (match Serialization.deserialize_from_file artifact_path with
           | Ok v -> v
           | Error e ->
               Error.runtime_error
                 (Printf.sprintf
                    "Function `get` failed to deserialize node artifact `%s` from `%s`: %s"
                    name artifact_path e))
        else
          Error.missing_artifact_error
            (Printf.sprintf "Artifact file %s does not exist." artifact_path)
    | None ->
        Error.missing_artifact_error
          (Printf.sprintf "Environment variable %s not found." env_name)
  in

  let apply_lens lens data _env_ref =
    let rec get_lens l d =
      match l with
      | ColLens col_name ->
          (match d with
           | VDataFrame df -> 
               (match Arrow_table.get_column df.arrow_table col_name with
                | Some col -> VVector (Arrow_bridge.column_to_values col)
                | None -> (VNA NAGeneric))
           | VDict items -> (match List.assoc_opt col_name items with Some v -> v | None -> (VNA NAGeneric))
           | VVector arr -> VVector (Array.map (fun v -> get_lens l v) arr)
           | VList items -> VList (List.map (fun (n, v) -> (n, get_lens l v)) items)
           | _ -> Error.type_error (Printf.sprintf "Lens get('%s') cannot be applied to %s" col_name (Utils.type_name d)))
      | IdxLens i ->
          (match d with
           | VList items ->
               let len = List.length items in
               if i < 0 || i >= len then Error.index_error i len
               else let (_, v) = List.nth items i in v
           | VVector arr ->
               let len = Array.length arr in
               if i < 0 || i >= len then Error.index_error i len
               else arr.(i)
           | _ -> Error.type_error (Printf.sprintf "idx_lens get expects a List or Vector, got %s" (Utils.type_name d)))
      | RowLens i ->
          (match d with
           | VDataFrame df ->
               let nrows = Arrow_table.num_rows df.arrow_table in
               if i < 0 || i >= nrows then Error.index_error i nrows
               else VDict (Arrow_bridge.row_to_dict df.arrow_table i)
           | _ -> Error.type_error (Printf.sprintf "row_lens get expects a DataFrame, got %s" (Utils.type_name d)))
       | NodeLens name ->
           (match d with
            | VPipeline p ->
                (match List.assoc_opt name p.p_nodes with
                 | Some v -> v
                 | None -> (VNA NAGeneric))
            | _ -> get_node_from_env name)
      | NodeMetaLens (name, field) ->
          (match d with
           | VPipeline p ->
               (match field with
                | "runtime" -> (match List.assoc_opt name p.p_runtimes with Some v -> VString v | None -> (VNA NAGeneric))
                | "noop" -> (match List.assoc_opt name p.p_noops with Some v -> VBool v | None -> (VNA NAGeneric))
                | "serializer" -> (match List.assoc_opt name p.p_serializers with Some e -> VExpr e | None -> (VNA NAGeneric))
                | "deserializer" -> (match List.assoc_opt name p.p_deserializers with Some e -> VExpr e | None -> (VNA NAGeneric))
                | _ -> (VNA NAGeneric))
           | _ -> Error.type_error "node_meta_lens get expects a Pipeline")
      | CompositeLens (l1, l2) ->
          let inner = get_lens l1 d in
          (match inner with
           | VError _ as e -> e
           | _ -> get_lens l2 inner)
      | EnvVarLens (node, var) ->
          (match d with
           | VPipeline p ->
               (match List.assoc_opt node p.p_env_vars with
                | Some vars -> (match List.assoc_opt var vars with Some v -> v | None -> (VNA NAGeneric))
                | None -> (VNA NAGeneric))
           | _ -> Error.type_error "env_var_lens get expects a Pipeline")
       | FilterLens p ->
           let evaluate_predicate v =
             match eval_call env p [(None, mk_expr (Value v))] with
             | VBool b -> Ok b
             | VError _ as e -> Error e
             | other ->
                 Error
                   (Error.type_error
                      (Printf.sprintf "filter_lens predicate must return Bool, got %s"
                         (Utils.type_name other)))
           in
           (match d with
            | VList items ->
                 let rec aux acc = function
                   | [] -> Ok (List.rev acc)
                   | (name, v) :: rest ->
                       (match evaluate_predicate v with
                        | Ok true -> aux ((name, v) :: acc) rest
                        | Ok false -> aux acc rest
                        | Error e -> Error e)
                in
                (match aux [] items with
                 | Ok filtered -> VList filtered
                 | Error e -> e)
            | VVector arr ->
                 let rec aux acc = function
                   | [] -> Ok (List.rev acc)
                   | v :: rest ->
                       (match evaluate_predicate v with
                        | Ok true -> aux (v :: acc) rest
                        | Ok false -> aux acc rest
                        | Error e -> Error e)
                in
                (match aux [] (Array.to_list arr) with
                 | Ok filtered -> VVector (Array.of_list filtered)
                 | Error e -> e)
            | VDataFrame df ->
                let nrows = Arrow_table.num_rows df.arrow_table in
                let keep = Array.make nrows false in
                 let rec aux i =
                   if i >= nrows then Ok ()
                   else
                     let row_dict = VDict (Arrow_bridge.row_to_dict df.arrow_table i) in
                     match evaluate_predicate row_dict with
                     | Ok b -> keep.(i) <- b; aux (i + 1)
                     | Error e -> Error e
                in
                (match aux 0 with
                 | Ok () ->
                     VDataFrame
                       { arrow_table = Arrow_compute.filter df.arrow_table keep
                       ; group_keys = df.group_keys
                       }
                 | Error e -> e)
            | VPipeline pipe ->
                let depths = Pipeline_to_frame.compute_depths pipe.p_deps in
                 let rec aux acc = function
                   | [] -> Ok (List.rev acc)
                   | (name, v) :: rest ->
                       let meta = VDict (Pipeline_to_frame.node_metadata_dict name pipe depths) in
                       (match evaluate_predicate meta with
                        | Ok true -> aux ((Some name, v) :: acc) rest
                        | Ok false -> aux acc rest
                        | Error e -> Error e)
                in
                (match aux [] pipe.p_nodes with
                 | Ok filtered -> VList filtered
                 | Error e -> e)
            | other ->
                Error.type_error
                  (Printf.sprintf "filter_lens expected collection, got %s"
                     (Utils.type_name other)))
     in
     get_lens lens data
   in

  Env.add "get"
    (make_builtin ~name:"get" ~variadic:true 1 (fun args env ->
      let args_vals = args in
      match args_vals with
      (* Variable Lookup Case (1 arg) *)
      | [VString name] | [VSymbol name] ->
          (match Env.find_opt name env with
           | Some v -> v
           | None -> Error.name_error name)

       (* Lens/Node Fallback Case (1 arg: Lens) *)
       | [VLens (NodeLens name)] ->
           get_node_from_env name
       | [VLens _l] ->
           Error.type_error "Single-argument get() with a lens requires a node_lens to perform environment-based retrieval."

      (* Pipeline Node Lookup (2 args: Pipeline, String/Symbol) *)
      | [VPipeline p; VString node_name] | [VPipeline p; VSymbol node_name] ->
          (match List.assoc_opt node_name p.p_nodes with
           | Some v -> v
           | None -> (VNA NAGeneric))

      (* Lens Case (2 args: Data, Lens) *)
      | [data; VLens l] ->
          apply_lens l data (ref env)

      (* Collection Indexing Case (2 args: Collection, Int) *)
      | [VList items; VInt i] ->
          let len = List.length items in
          if i < 0 || i >= len then Error.index_error i len
          else let (_, v) = List.nth items i in v
      | [VVector arr; VInt i] ->
          let len = Array.length arr in
          if i < 0 || i >= len then Error.index_error i len
          else arr.(i)
      | [VNDArray arr; VInt i] ->
          let len = Array.length arr.data in
          if i < 0 || i >= len then Error.index_error i len
          else VFloat arr.data.(i)

      (* Fallback with Default (2 args: NA/Error, Default) *)
      | [VNA _; default] | [VError _; default] ->
          default

      (* Fallback: legacy VDict lens support? *)
      | [data; VDict items] ->
          (match List.assoc_opt "get" items with
           | Some get_fn -> eval_call env get_fn [(None, mk_expr (Value data))]
           | None -> Error.type_error "Function `get`: Data and Dict provided, but Dict is not a valid lens.")

      (* 3-argument case: get(target, selector, default) *)
      | [target; selector; default] ->
          let res = 
            match [target; selector] with
            | [VPipeline p; VString node_name] | [VPipeline p; VSymbol node_name] ->
                (match List.assoc_opt node_name p.p_nodes with Some v -> v | None -> (VNA NAGeneric))
            | [data; VLens l] -> apply_lens l data (ref env)
            | [VList items; VInt i] ->
                let len = List.length items in
                if i < 0 || i >= len then (VNA NAGeneric)
                else let (_, v) = List.nth items i in v
            | [VVector arr; VInt i] ->
                let len = Array.length arr in
                if i < 0 || i >= len then (VNA NAGeneric)
                else arr.(i)
            | [VNDArray arr; VInt i] ->
                let len = Array.length arr.data in
                if i < 0 || i >= len then (VNA NAGeneric)
                else VFloat arr.data.(i)
            | _ ->
                Error.type_error
                  (Printf.sprintf
                     "Function `get` (3 args) expects (Pipeline, String, Default), (Collection, Int, Default), or (Data, Lens, Default), got (%s, %s, _)."
                     (Utils.type_name target) (Utils.type_name selector))
          in
          (match res with
           | VNA _ -> default
           | _ -> res)

       | [v] -> Error.type_error (Printf.sprintf "Function `get` (1 arg) expects a String or Symbol, got %s." (Utils.type_name v))
       (* Catch-all 2-arg case: return first arg unchanged.
          NA and Error 2-arg cases are handled by earlier match arms above,
          so this arm is only reached for non-NA/non-Error first arguments
          that did not match any specific retrieval pattern. *)
       | [v; _] -> v
       | _ -> Error.arity_error_named "get" 1 (List.length args)
     ))
     env