Class: SkillBench::HistoryRecorder::HistoryFile

Inherits:
Object
  • Object
show all
Defined in:
lib/skill_bench/history_recorder/history_file.rb

Overview

Handles atomic read/write of benchmark history JSON files.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.load(path) ⇒ Array<Hash>

Loads history from the given path.

Parameters:

  • path (String)

    path to the JSON history file

Returns:

  • (Array<Hash>)

    parsed history entries



14
15
16
# File 'lib/skill_bench/history_recorder/history_file.rb', line 14

def self.load(path)
  new.load(path)
end

.write(path, data) ⇒ void

This method returns an undefined value.

Writes history data atomically to the given path.

Parameters:

  • path (String)

    target file path

  • data (Array<Hash>)

    history entries to serialize



23
24
25
# File 'lib/skill_bench/history_recorder/history_file.rb', line 23

def self.write(path, data)
  new.write(path, data)
end

Instance Method Details

#load(path) ⇒ Array<Hash>

Loads history from the given path.

Parameters:

  • path (String)

    path to the JSON history file

Returns:

  • (Array<Hash>)

    parsed history entries



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/skill_bench/history_recorder/history_file.rb', line 31

def load(path)
  return [] unless File.exist?(path)

  JSON.parse(File.read(path), symbolize_names: true)
rescue JSON::ParserError => e
  SkillBench::ErrorLogger.log_error(e, 'corrupted benchmarks.json')
  []
rescue StandardError => e
  SkillBench::ErrorLogger.log_error(e, 'HistoryRecorder')
  []
end

#write(path, data) ⇒ void

This method returns an undefined value.

Writes history data atomically using a temp file and rename.

Parameters:

  • path (String)

    target file path

  • data (Array<Hash>)

    history entries to serialize



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/skill_bench/history_recorder/history_file.rb', line 48

def write(path, data)
  dir = File.dirname(path)
  FileUtils.mkpath(dir)

  temp_path = "#{path}.tmp.#{Process.pid}"
  File.open(temp_path, File::WRONLY | File::CREAT | File::TRUNC, 0o644) do |file|
    file.flock(File::LOCK_EX)
    file.write(JSON.pretty_generate(data))
    file.fsync
  end
  File.rename(temp_path, path)
  logger&.info("History recorded to #{path}")
end