From ac24a8c547609fdc98cfd387e262ae6784ae1440 Mon Sep 17 00:00:00 2001 From: Anthony Khong Date: Tue, 8 Sep 2026 12:52:22 +0700 Subject: [PATCH] refactor incidental complexity --- lib/latu/ml.ex | 144 ++++++++++++++++++---------------------- lib/latu/ml/internal.ex | 9 ++- lib/latu/ml/layout.ex | 63 ++++++++++-------- lib/latu/ml/result.ex | 28 +++----- 4 files changed, 119 insertions(+), 125 deletions(-) diff --git a/lib/latu/ml.ex b/lib/latu/ml.ex index 9c685dd..c7ec181 100644 --- a/lib/latu/ml.ex +++ b/lib/latu/ml.ex @@ -513,19 +513,32 @@ defmodule Latu.ML do # per param map, and re-deriving a filtered random draw that many times is the one avoidable # cost in a search. PySpark does the same, for the same reason. defp score_fold(validator, train, validation) do - with {:ok, train} <- Latu.persist(train), - {:ok, validation} <- Latu.persist(validation) do - result = score_grid(validator, train, validation) + case Latu.persist(train) do + {:ok, train} -> + case Latu.persist(validation) do + {:ok, validation} -> + scored(validator, train, validation) + + # A persist is a resource like any other, so the one that succeeded goes back. + {:error, error} -> + Latu.unpersist(train) + {:error, error, []} + end + + {:error, error} -> + {:error, error, []} + end + end - Latu.unpersist(train) - Latu.unpersist(validation) + defp scored(validator, train, validation) do + result = score_grid(validator, train, validation) - case result do - {:ok, metrics, kept} -> {:ok, Enum.reverse(metrics), Enum.reverse(kept)} - other -> other - end - else - {:error, error} -> {:error, error, []} + Latu.unpersist(train) + Latu.unpersist(validation) + + case result do + {:ok, metrics, kept} -> {:ok, Enum.reverse(metrics), Enum.reverse(kept)} + other -> other end end @@ -561,6 +574,37 @@ defmodule Latu.ML do defp collected(kept), do: kept |> List.flatten() |> Enum.flat_map(&cached_models/1) + # Collect in order, or give back what was already cached and answer with the first error. + # A `Read` caches, so every error path below one owns what it read. That decision lives here + # rather than at each fold, because five copies of it is how the sixth came to forget. + defp traverse(items, fun) do + items + |> Enum.reduce_while({:ok, []}, fn item, {:ok, done} -> + case fun.(item) do + {:ok, value} -> {:cont, {:ok, [value | done]}} + {:error, error} -> {:halt, {:error, error, done}} + end + end) + |> case do + {:ok, done} -> + {:ok, Enum.reverse(done)} + + {:error, error, done} -> + release(collected(done)) + {:error, error} + end + end + + # `:ok`, or the first error. Nothing is cached on this path, so nothing is given back. + defp each_ok(items, fun) do + Enum.reduce_while(items, :ok, fn item, :ok -> + case fun.(item) do + :ok -> {:cont, :ok} + {:error, error} -> {:halt, {:error, error}} + end + end) + end + defp transpose([]), do: [] defp transpose(rows), do: rows |> Enum.zip() |> Enum.map(&Tuple.to_list/1) @@ -1221,12 +1265,7 @@ defmodule Latu.ML do defp save_sub_models(session, %CrossValidatorModel{} = model, path, opts) do model.sub_models |> Enum.with_index() - |> Enum.reduce_while(:ok, fn {fold, index}, :ok -> - case save_fold(session, fold, path, index, opts) do - :ok -> {:cont, :ok} - {:error, error} -> {:halt, {:error, error}} - end - end) + |> each_ok(fn {fold, index} -> save_fold(session, fold, path, index, opts) end) end defp save_sub_models(session, %TrainValidationSplitModel{} = model, path, opts) do @@ -1236,13 +1275,8 @@ defmodule Latu.ML do defp save_fold(session, models, path, fold, opts) do models |> Enum.with_index() - |> Enum.reduce_while(:ok, fn {model, index}, :ok -> - where = Layout.sub_model_path(path, fold, index) - - case save_stage(session, model, where, opts) do - :ok -> {:cont, :ok} - {:error, error} -> {:halt, {:error, error}} - end + |> each_ok(fn {model, index} -> + save_stage(session, model, Layout.sub_model_path(path, fold, index), opts) end) end @@ -1257,13 +1291,9 @@ defmodule Latu.ML do :ok <- Layout.write_metadata(session, path, kind, uid, stage_map(stages)) do stages |> Enum.with_index() - |> Enum.reduce_while(:ok, fn {stage, index}, :ok -> + |> each_ok(fn {stage, index} -> where = Layout.stage_path(path, index, stage.uid, length(stages)) - - case save_stage(session, stage, where, opts) do - :ok -> {:cont, :ok} - {:error, error} -> {:halt, {:error, error}} - end + save_stage(session, stage, where, opts) end) end end @@ -1457,41 +1487,11 @@ defmodule Latu.ML do end defp read_folds(session, path, folds, width) do - folds - |> Enum.reduce_while({:ok, []}, fn fold, {:ok, done} -> - case read_fold(session, path, fold, width) do - {:ok, models} -> {:cont, {:ok, [models | done]}} - {:error, error} -> {:halt, {:error, error, List.flatten(done)}} - end - end) - |> case do - {:ok, folds} -> - {:ok, Enum.reverse(folds)} - - {:error, error, orphans} -> - release(collected(orphans)) - {:error, error} - end + traverse(folds, &read_fold(session, path, &1, width)) end - # A `Read` caches, so a partial load orphans what it already read. Third place this shape - # appears, after the pipeline fold and `load_stages`. defp read_fold(session, path, fold, width) do - 0..(width - 1) - |> Enum.reduce_while({:ok, []}, fn index, {:ok, done} -> - case load_stage(session, Layout.sub_model_path(path, fold, index)) do - {:ok, model} -> {:cont, {:ok, [model | done]}} - {:error, error} -> {:halt, {:error, error, done}} - end - end) - |> case do - {:ok, models} -> - {:ok, Enum.reverse(models)} - - {:error, error, orphans} -> - release(collected(orphans)) - {:error, error} - end + traverse(0..(width - 1), &load_stage(session, Layout.sub_model_path(path, fold, &1))) end defp rebuilt_search(kind, uid, estimator, evaluator, params, name_of) do @@ -1579,23 +1579,9 @@ defmodule Latu.ML do defp load_stages(session, path, uids) do uids |> Enum.with_index() - |> Enum.reduce_while({:ok, []}, fn {uid, index}, {:ok, done} -> - case load_stage(session, Layout.stage_path(path, index, uid, length(uids))) do - {:ok, stage} -> {:cont, {:ok, [stage | done]}} - {:error, error} -> {:halt, {:error, error, done}} - end + |> traverse(fn {uid, index} -> + load_stage(session, Layout.stage_path(path, index, uid, length(uids))) end) - |> case do - {:ok, stages} -> - {:ok, Enum.reverse(stages)} - - # A `Read` caches, so the stages that did load are entries nothing asked for and nothing - # else will give back. Same shape as a fit that fails partway, and released the same way. - {:error, error, done} -> - done |> Enum.flat_map(&cached_models/1) |> release() - - {:error, error} - end end # A stage says what it is in its own metadata, which is the only thing that does: a directory @@ -1812,7 +1798,7 @@ defmodule Latu.ML do end) |> case do {:ok, decoded} -> {:ok, Enum.reverse(decoded)} - {:error, error} -> {:error, error} + error -> error end end diff --git a/lib/latu/ml/internal.ex b/lib/latu/ml/internal.ex index d97b5e1..210ff29 100644 --- a/lib/latu/ml/internal.ex +++ b/lib/latu/ml/internal.ex @@ -976,11 +976,16 @@ defmodule Latu.ML.Internal do {:ok, Model.t()} | {:error, Latu.Error.t()} def model_from_helper(name, session, values, opts) do row = Registry.helper!(name) - known = with %{params: params} <- Registry.operator_of_class(row.model_class), do: params + + known = + case Registry.operator_of_class(row.model_class) do + %{params: params} -> params + nil -> [] + end with {:ok, %Model{} = model} <- Latu.ML.helper(session, name, [uid(row.model_class) | values]) do - {:ok, %Model{model | params: params!(opts, known || [])}} + {:ok, %Model{model | params: params!(opts, known)}} end end diff --git a/lib/latu/ml/layout.ex b/lib/latu/ml/layout.ex index 481260b..e37a035 100644 --- a/lib/latu/ml/layout.ex +++ b/lib/latu/ml/layout.ex @@ -43,35 +43,44 @@ defmodule Latu.ML.Layout do @stages "stages" @sub_models "subModels" - # What PySpark writes for each. `Latu.ML.load/4` dispatches on it and so does Scala's reader, - # which `require`s an exact match; PySpark 4.2's own pipeline reader ignores it entirely. - @classes %{ - pipeline: "pyspark.ml.pipeline.Pipeline", - pipeline_model: "pyspark.ml.pipeline.PipelineModel", - cross_validator: "pyspark.ml.tuning.CrossValidator", - cross_validator_model: "pyspark.ml.tuning.CrossValidatorModel", - train_validation_split: "pyspark.ml.tuning.TrainValidationSplit", - train_validation_split_model: "pyspark.ml.tuning.TrainValidationSplitModel" - } - - # Which of them lay out a directory of stages, and which lay out a search. Both are read by - # `class`, so something has to say them apart — ML5a could assume every known class here was - # a pipeline and no longer can. - @shapes %{ - pipeline: :stages, - pipeline_model: :stages, - cross_validator: :search, - cross_validator_model: :search, - train_validation_split: :search, - train_validation_split_model: :search + # One row per meta-algorithm. Three things get asked about a kind, and three tables keyed by + # the same six atoms were three places to remember when a seventh arrives — only one of which + # would have failed the compile. + # + # * `class` is what PySpark writes. `Latu.ML.load/4` dispatches on it and so does Scala's + # reader, which `require`s an exact match; PySpark 4.2's own pipeline reader ignores it + # entirely. + # * `shape` is which of them lay out a directory of stages and which lay out a search. Both + # are read by their class, so something has to say them apart — ML5a could assume every + # known class here was a pipeline and no longer can. + # * `fitted` is which of them have models in them. + @kinds %{ + pipeline: %{class: "pyspark.ml.pipeline.Pipeline", shape: :stages, fitted: false}, + pipeline_model: %{class: "pyspark.ml.pipeline.PipelineModel", shape: :stages, fitted: true}, + cross_validator: %{class: "pyspark.ml.tuning.CrossValidator", shape: :search, fitted: false}, + cross_validator_model: %{ + class: "pyspark.ml.tuning.CrossValidatorModel", + shape: :search, + fitted: true + }, + train_validation_split: %{ + class: "pyspark.ml.tuning.TrainValidationSplit", + shape: :search, + fitted: false + }, + train_validation_split_model: %{ + class: "pyspark.ml.tuning.TrainValidationSplitModel", + shape: :search, + fitted: true + } } @doc "The `class` string a kind of meta-algorithm is saved under." - def class(kind), do: Map.fetch!(@classes, kind) + def class(kind), do: Map.fetch!(@kinds, kind).class @doc "Which kind a `class` string names, or nil for anything that is not one of ours." def kind(class) do - Enum.find_value(@classes, fn {kind, name} -> if name == class, do: kind end) + Enum.find_value(@kinds, fn {kind, %{class: name}} -> if name == class, do: kind end) end @doc """ @@ -81,12 +90,12 @@ defmodule Latu.ML.Layout do that. Two shapes, and nothing outside this module should be matching class strings to tell them apart. """ - def shape(kind), do: Map.fetch!(@shapes, kind) + def shape(kind), do: Map.fetch!(@kinds, kind).shape @doc "Whether a kind is a fitted thing (it has models in it) or an unfitted one." - def fitted?(kind) do - kind in [:pipeline_model, :cross_validator_model, :train_validation_split_model] - end + # Unlike the two above, this answers for a kind the table does not name: it replaced a + # membership test, which said false to everything that was not in its list. + def fitted?(kind), do: Map.get(@kinds, kind, %{fitted: false}).fitted @doc """ Write `/metadata`. diff --git a/lib/latu/ml/result.ex b/lib/latu/ml/result.ex index 2d8fdba..8262ba6 100644 --- a/lib/latu/ml/result.ex +++ b/lib/latu/ml/result.ex @@ -23,14 +23,13 @@ defmodule Latu.ML.Result do @spec object_ref(struct()) :: {:ok, Latu.ML.Plan.object_ref()} | {:error, Error.t()} def object_ref(execution) - def object_ref(%{ml_command_result: %{result_type: result_type}}) - when elem(result_type, 0) == :operator_info do - case elem(result_type, 1) do - %{type: {:obj_ref, ref}} -> {:ok, ref.id} - _info -> {:error, protocol_error("a Fit answered with no object reference")} - end + def object_ref(%{ml_command_result: %{result_type: {:operator_info, %{type: {:obj_ref, ref}}}}}) do + {:ok, ref.id} end + def object_ref(%{ml_command_result: %{result_type: {:operator_info, _info}}}), + do: {:error, protocol_error("a Fit answered with no object reference")} + def object_ref(execution), do: {:error, unexpected(execution, "an object reference")} @doc """ @@ -81,10 +80,7 @@ defmodule Latu.ML.Result do @spec operator_info(struct()) :: {:ok, operator_info()} | {:error, Error.t()} def operator_info(execution) - def operator_info(%{ml_command_result: %{result_type: result_type}}) - when elem(result_type, 0) == :operator_info do - info = elem(result_type, 1) - + def operator_info(%{ml_command_result: %{result_type: {:operator_info, info}}}) do with {:ok, params} <- params(info.params) do {:ok, %{ref: ref(info.type), name: name(info.type), uid: info.uid, params: params}} end @@ -225,13 +221,11 @@ defmodule Latu.ML.Result do @spec operators(struct()) :: {:ok, [Latu.ML.Plan.object_ref()]} | {:error, Error.t()} def operators(execution) - def operators(%{ml_command_result: %{result_type: result_type}}) - when elem(result_type, 0) == :operator_info do - case elem(result_type, 1) do - %{type: {:obj_ref, ref}} -> {:ok, String.split(ref.id, ",", trim: true)} - _info -> {:error, protocol_error("a list of operators answered with no object reference")} - end - end + def operators(%{ml_command_result: %{result_type: {:operator_info, %{type: {:obj_ref, ref}}}}}), + do: {:ok, String.split(ref.id, ",", trim: true)} + + def operators(%{ml_command_result: %{result_type: {:operator_info, _info}}}), + do: {:error, protocol_error("a list of operators answered with no object reference")} def operators(execution), do: {:error, unexpected(execution, "a list of operators")}