Download lib/forge/tournament/tournament.ex from Snapkitty/forge-code: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/datasets/Snapkitty/forge-code/resolve/main/lib/forge/tournament/tournament.ex
- Command line
-
hf download hf://datasets/Snapkitty/forge-code/lib/forge/tournament/tournament.ex
-
curl -L -o tournament.ex https://huggingface.co/datasets/Snapkitty/forge-code/resolve/main/lib/forge/tournament/tournament.ex
15.7 kB
| defmodule Forge.Tournament do | |
| @moduledoc """ | |
| Tournament - Orchestrates competitive benchmarking of Elixir implementations. | |
| This module provides the main tournament orchestration, managing contestants, | |
| challenges, execution, and scoring. It ensures deterministic comparison | |
| of multiple Elixir implementations solving the same computational problem. | |
| ## Usage | |
| # Define a tournament | |
| Forge.Tournament.define "Integer Hashing" do | |
| challenge "sha256" do | |
| input "forge" | |
| expected "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" | |
| end | |
| end | |
| # Run a tournament | |
| {:ok, results} = Forge.Tournament.run("path/to/tournament.exs") | |
| """ | |
| alias Forge.Compiler | |
| alias Forge.Provenance | |
| alias Forge.Hash | |
| alias Forge.Score | |
| alias Forge.Judge | |
| alias Forge.Runner | |
| @type tournament_id :: String.t() | |
| @type contestant_id :: String.t() | |
| @type challenge_id :: String.t() | |
| @type challenge :: %{ | |
| id: challenge_id(), | |
| description: String.t(), | |
| input: any(), | |
| expected: any(), | |
| timeout: integer(), | |
| memory_limit: integer() | |
| } | |
| @type contestant :: %{ | |
| id: contestant_id(), | |
| name: String.t(), | |
| source_path: String.t(), | |
| module: atom(), | |
| function: atom(), | |
| compiled: boolean(), | |
| beam_path: String.t() | nil, | |
| provenance: Provenance.provenance_chain() | nil | |
| } | |
| @type tournament_result :: %{ | |
| tournament_id: tournament_id(), | |
| contestants: list(contestant()), | |
| challenges: list(challenge()), | |
| results: list(Forge.Judge.judge_result()), | |
| scores: list(Forge.Score.score_result()), | |
| overall_ranking: list(map()), | |
| metadata: map() | |
| } | |
| @doc """ | |
| Defines a new tournament configuration. | |
| This is the entry point for creating tournament DSL files. | |
| """ | |
| defmacro define(name, do: block) do | |
| # Parse the challenge definitions from the block | |
| challenges = extract_challenges(block) | |
| # Generate a tournament module | |
| module_name = String.to_atom("Forge.Tournament." <> String.replace(name, ~r/[^a-zA-Z0-9_]/, "_")) | |
| quote bind_quoted: [name: name, challenges: challenges, module_name: module_name] do | |
| defmodule module_name do | |
| @tournament_name name | |
| @challenges challenges | |
| def get_name, do: @tournament_name | |
| def get_challenges, do: @challenges | |
| end | |
| # Return the module for immediate use | |
| module_name | |
| end | |
| end | |
| @doc """ | |
| Extracts challenge definitions from a quote block. | |
| """ | |
| defp extract_challenges(block) do | |
| Enum.filter_map(block, fn | |
| {:challenge, _, [challenge_definition]} -> | |
| extract_challenge_config(challenge_definition) | |
| _ -> nil | |
| end) | |
| end | |
| @doc """ | |
| Extracts configuration from a challenge definition. | |
| """ | |
| defp extract_challenge_config({:do, _, block}) do | |
| config = %{id: nil, description: nil, input: nil, expected: nil, timeout: 5000, memory_limit: 128_000} | |
| Enum.reduce(block, config, fn | |
| {:input, _, [value]}, acc -> %{acc | input: value} | |
| {:expected, _, [value]}, acc -> %{acc | expected: value} | |
| {:id, _, [id]}, acc -> %{acc | id: id} | |
| {:description, _, [desc]}, acc -> %{acc | description: desc} | |
| {:timeout, _, [t]}, acc -> %{acc | timeout: t} | |
| {:memory_limit, _, [m]}, acc -> %{acc | memory_limit: m} | |
| _ , acc -> acc | |
| end) | |
| end | |
| @doc """ | |
| Runs a tournament from a definition file. | |
| ## Parameters | |
| - path: Path to the tournament definition file (.exs) | |
| - options: Tournament options | |
| ## Returns | |
| - {:ok, tournament_result} on success | |
| - {:error, reason} on failure | |
| """ | |
| @spec run(String.t(), map()) :: {:ok, tournament_result()} | {:error, String.t()} | |
| def run(path, options \ []) do | |
| default_options = %{ | |
| sandbox: true, | |
| capture_output: true, | |
| verbose: false | |
| } | |
| options = Map.merge(default_options, options) | |
| # Load the tournament definition | |
| case load_tournament_definition(path) do | |
| {:ok, tournament_module} -> | |
| tournament_name = tournament_module.get_name() | |
| challenges = tournament_module.get_challenges() | |
| # Find contestant submissions | |
| contestants = find_contestants(path) | |
| if length(contestants) == 0 do | |
| {:error, "No contestants found for tournament #{tournament_name}"} | |
| else | |
| # Compile all contestants | |
| compiled_contestants = compile_contestants(contestants, options) | |
| # Run each challenge | |
| results = Enum.flat_map(challenges, fn challenge -> | |
| run_challenge(challenge, compiled_contestants, options) | |
| end) | |
| # Calculate scores | |
| scores = Score.calculate_all(results) | |
| # Generate overall ranking | |
| ranking = calculate_ranking(scores) | |
| result = %{ | |
| tournament_id: tournament_name, | |
| contestants: compiled_contestants, | |
| challenges: challenges, | |
| results: results, | |
| scores: scores, | |
| overall_ranking: ranking, | |
| metadata: %{ | |
| timestamp: DateTime.utc_now(), | |
| otp_version: System.get_env("OTP_VERSION") || System.version(), | |
| elixir_version: System.get_env("ELIXIR_VERSION") || to_string(:elixir), | |
| options: options | |
| } | |
| } | |
| {:ok, result} | |
| end | |
| {:error, reason} -> | |
| {:error, "Failed to load tournament: #{reason}"} | |
| end | |
| end | |
| @doc """ | |
| Loads a tournament definition file. | |
| """ | |
| defp load_tournament_definition(path) do | |
| try do | |
| # Check if the file uses the Forge.Tournament.define macro | |
| if String.contains?(File.read!(path), "Forge.Tournament.define") do | |
| # Load the module dynamically | |
| module_name = String.replace(Path.basename(path), ".exs", "") |> String.capitalize() | |
| code = File.read!(path) | |
| # Compile the tournament definition | |
| {:module, _, binary, _} = Code.eval_string(code, [], []) | |
| # Load the module | |
| Module.concat(binary) | |
| # Find the tournament module | |
| tournament_module = Module.concat([:forge, :tournament, String.to_atom(module_name)]) | |
| {:ok, tournament_module} | |
| else | |
| {:error, "Invalid tournament definition format"} | |
| end | |
| rescue | |
| e -> {:error, "Failed to load tournament: #{inspect(e)}"} | |
| end | |
| end | |
| @doc """ | |
| Finds contestant submissions for a tournament. | |
| Looks for .ex files in the same directory as the tournament file. | |
| """ | |
| defp find_contestants(tournament_path) do | |
| dir = Path.dirname(tournament_path) | |
| case File.ls(dir) do | |
| {:ok, files} -> | |
| Enum.filter_map(files, fn file -> | |
| if String.ends_with?(file, ".ex") && !String.starts_with?(file, ".") do | |
| # Extract contestant info from filename or module | |
| path = Path.join(dir, file) | |
| source = File.read!(path) | |
| # Try to extract module name | |
| module_name = extract_module_name(source) | |
| function_name = extract_function_name(source) | |
| # Generate contestant ID | |
| contestant_id = String.replace(Path.basename(file), ".ex", "") | |
| %{ | |
| id: contestant_id, | |
| name: contestant_id, | |
| source_path: path, | |
| module: module_name || String.to_atom(contestant_id), | |
| function: function_name || :solve, | |
| compiled: false, | |
| beam_path: nil, | |
| provenance: nil | |
| } | |
| else | |
| nil | |
| end | |
| end) | |
| {:error, _} -> [] | |
| end | |
| end | |
| @doc """ | |
| Extracts module name from source code. | |
| """ | |
| defp extract_module_name(source) do | |
| case String.split(source, "\n") |> Enum.find_value(fn line -> | |
| if String.starts_with?(line, "defmodule ") do | |
| String.trim(line) |> String.replace("defmodule ", "") |> String.replace(" do", "") |> String.trim() | |
| else | |
| nil | |
| end | |
| end) do | |
| nil -> nil | |
| module_str -> String.to_atom(String.replace(module_str, ".", "_")) | |
| end | |
| end | |
| @doc """ | |
| Extracts function name from source code. | |
| """ | |
| defp extract_function_name(source) do | |
| case String.split(source, "\n") |> Enum.find_value(fn line -> | |
| if String.contains?(line, "def ") && !String.contains?(line, "defp") && !String.contains?(line, "defmodule") do | |
| # Extract function name and arity | |
| String.trim(line) |> String.replace("def ", "") |> String.split("(") |> List.first() |> String.trim() | |
| else | |
| nil | |
| end | |
| end) do | |
| nil -> :solve | |
| func -> String.to_atom(func) | |
| end | |
| end | |
| @doc """ | |
| Compiles all contestant submissions. | |
| """ | |
| defp compile_contestants(contestants, options) do | |
| Enum.map(contestants, fn contestant -> | |
| case compile_contestant(contestant, options) do | |
| {:ok, compiled} -> compiled | |
| {:error, _reason} -> %{contestant | compiled: false} | |
| end | |
| end) | |
| end | |
| @doc """ | |
| Compiles a single contestant submission. | |
| """ | |
| defp compile_contestant(contestant, options) do | |
| case File.read(contestant.source_path) do | |
| {:ok, source} -> | |
| compile_options = %{ | |
| compiler_flags: options[:compiler_flags] || [], | |
| sandbox: options[:sandbox] || true, | |
| timeout: options[:timeout] || 30_000 | |
| } | |
| case Compiler.compile(source, compile_options) do | |
| {:ok, result} -> | |
| beam_path = result.beam_path | |
| provenance = result.provenance | |
| %{ | |
| contestant | | |
| compiled: true, | |
| beam_path: beam_path, | |
| provenance: provenance | |
| } | |
| {:error, _reason, details} -> | |
| # Even if compilation failed, keep the contestant | |
| %{ | |
| contestant | | |
| compiled: false, | |
| beam_path: nil, | |
| provenance: details.provenance || nil | |
| } | |
| end | |
| {:error, _reason} -> | |
| {:error, "Failed to read contestant source: #{contestant.source_path}"} | |
| end | |
| end | |
| @doc """ | |
| Runs a single challenge for all contestants. | |
| """ | |
| defp run_challenge(challenge, contestants, options) do | |
| Enum.map(contestants, fn contestant -> | |
| if contestant.compiled do | |
| case Runner.execute(contestant, challenge, options) do | |
| {:ok, result} -> result | |
| {:error, reason} -> | |
| %Forge.Judge.JudgeResult{ | |
| contestant_id: contestant.id, | |
| challenge_id: challenge.id, | |
| passed: false, | |
| execution_time: nil, | |
| memory_used: nil, | |
| output: nil, | |
| error: reason, | |
| timestamp: DateTime.utc_now() | |
| } | |
| end | |
| else | |
| # Contestant didn't compile - automatic failure | |
| %Forge.Judge.JudgeResult{ | |
| contestant_id: contestant.id, | |
| challenge_id: challenge.id, | |
| passed: false, | |
| execution_time: nil, | |
| memory_used: nil, | |
| output: nil, | |
| error: "Contestant failed to compile", | |
| timestamp: DateTime.utc_now() | |
| } | |
| end | |
| end) | |
| end | |
| @doc """ | |
| Calculates overall ranking from scores. | |
| """ | |
| defp calculate_ranking(scores) do | |
| # Group scores by contestant | |
| contestant_scores = Enum.group_by(scores, &(&1.contestant_id)) | |
| # Calculate average score per contestant | |
| ranked = Enum.map(contestant_scores, fn {contestant_id, scores} -> | |
| total_score = Enum.reduce(scores, 0, &(&1.total_score + &2)) | |
| avg_score = total_score / max(length(scores), 1) | |
| %{ | |
| contestant_id: contestant_id, | |
| average_score: avg_score, | |
| total_score: total_score, | |
| challenge_count: length(scores) | |
| } | |
| end) | |
| # Sort by average score (descending) | |
| ranked |> Enum.sort_by(&(-&1.average_score)) | |
| end | |
| @doc """ | |
| Creates a summary of tournament results. | |
| """ | |
| @spec summary(tournament_result()) :: String.t() | |
| def summary(result) do | |
| lines = [ | |
| "=" <> String.duplicate("=", 60), | |
| "FORGE TOURNAMENT RESULTS", | |
| "=" <> String.duplicate("=", 60), | |
| "", | |
| "Tournament: #{result.tournament_id}", | |
| "Contestants: #{length(result.contestants)}", | |
| "Challenges: #{length(result.challenges)}", | |
| "Timestamp: #{result.metadata.timestamp}", | |
| "", | |
| "-" <> String.duplicate("-", 60), | |
| "OVERALL RANKING", | |
| "-" <> String.duplicate("-", 60) | |
| ] | |
| # Add ranking table | |
| ranking_lines = Enum.map_with_index(result.overall_ranking, fn ranking, idx -> | |
| position = idx + 1 | |
| " #{position}. #{ranking.contestant_id} - Score: #{Float.round(ranking.average_score, 4)}" | |
| end) | |
| lines = lines ++ ranking_lines ++ [ | |
| "", | |
| "-" <> String.duplicate("-", 60), | |
| "CHALLENGE RESULTS", | |
| "-" <> String.duplicate("-", 60) | |
| ] | |
| # Add challenge results | |
| challenge_results = Enum.group_by(result.results, &(&1.challenge_id)) | |
| Enum.each(challenge_results, fn {challenge_id, results} -> | |
| lines = lines ++ ["\nChallenge: #{challenge_id}"] | |
| Enum.each(results, fn result -> | |
| status = if result.passed, do: "PASS", else: "FAIL" | |
| time = if result.execution_time, do: " (#{result.execution_time}ms)", else: "" | |
| lines = lines ++ [" #{result.contestant_id}: #{status}#{time}"] | |
| end) | |
| end) | |
| Enum.join(lines, "\n") | |
| end | |
| @doc """ | |
| Exports tournament results to JSON. | |
| """ | |
| @spec to_json(tournament_result()) :: String.t() | |
| def to_json(result) do | |
| # Convert to a JSON-serializable structure | |
| json_data = %{ | |
| tournament_id: result.tournament_id, | |
| contestants: Enum.map(result.contestants, &to_json_contestant/1), | |
| challenges: Enum.map(result.challenges, &to_json_challenge/1), | |
| results: Enum.map(result.results, &to_json_result/1), | |
| scores: Enum.map(result.scores, &to_json_score/1), | |
| ranking: result.overall_ranking, | |
| metadata: result.metadata | |
| } | |
| # Use Jason if available, otherwise simple encoding | |
| if Code.ensure_loaded?(Jason) do | |
| Jason.encode!(json_data) | |
| else | |
| :erlang.term_to_binary(json_data) |> to_string() | |
| end | |
| end | |
| defp to_json_contestant(contestant) do | |
| %{ | |
| id: contestant.id, | |
| name: contestant.name, | |
| compiled: contestant.compiled, | |
| module: Atom.to_string(contestant.module), | |
| function: Atom.to_string(contestant.function) | |
| } | |
| end | |
| defp to_json_challenge(challenge) do | |
| %{ | |
| id: challenge.id, | |
| description: challenge.description, | |
| timeout: challenge.timeout, | |
| memory_limit: challenge.memory_limit | |
| } | |
| end | |
| defp to_json_result(result) do | |
| %{ | |
| contestant_id: result.contestant_id, | |
| challenge_id: result.challenge_id, | |
| passed: result.passed, | |
| execution_time: result.execution_time, | |
| memory_used: result.memory_used, | |
| output: result.output, | |
| error: result.error, | |
| timestamp: DateTime.to_iso8601(result.timestamp) | |
| } | |
| end | |
| defp to_json_score(score) do | |
| %{ | |
| contestant_id: score.contestant_id, | |
| challenge_id: score.challenge_id, | |
| dimensions: Enum.map(score.dimensions, &{&1.dimension, &1.value, &1.weight}), | |
| total_score: score.total_score, | |
| weight_total: score.weight_total | |
| } | |
| end | |
| end | |