Module: Cohere::Transcribe::Output::Publication

Defined in:
lib/cohere/transcribe/output/publication.rb

Constant Summary collapse

OUTPUT_SCHEMA_VERSION =
8
PROFILE_SCHEMA_VERSION =
9
REPETITION_DETECTOR_VERSION =
3
SILERO_VERSION =
"6.2.1"
SUCCESSFUL_BATCH_PROFILE_FIELDS =
%w[
  segments processor_rows max_new_tokens generated_tokens generated_tokens_by_row
  prepare_seconds h2d_seconds generation_call_wall_seconds generate_device_seconds
  generation_analysis_seconds padded_audio_seconds padding_ratio peak_allocated_gib
  peak_reserved_gib
].freeze

Class Method Summary collapse

Class Method Details

.atomic_write_set(paths, contents, before_commit: nil, rename: nil, directory_bindings: nil, operation_hook: nil) ⇒ Object



846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
# File 'lib/cohere/transcribe/output/publication.rb', line 846

def atomic_write_set(paths, contents, before_commit: nil, rename: nil,
                     directory_bindings: nil, operation_hook: nil)
  staged = {}
  backups = {}
  committed = []
  preserved_backups = {}
  open_handles = []
  failed = false
  bound_directories = publication_bound_directories(paths, directory_bindings)
  operation_hook&.call(:directories_opened, nil)
  paths.each do |format, supplied_destination|
    destination = Pathname(supplied_destination).expand_path
    bound = bound_directories.fetch(destination.dirname)
    bound.verify!
    output_mode = bound_output_mode(bound, destination.basename.to_s)
    temporary_name = nil
    temporary = nil
    Thread.handle_interrupt(State::DEFERRED_PUBLICATION_EXCEPTIONS) do
      temporary_name, temporary = bound.create_temporary(destination.basename.to_s, ".tmp")
      staged[destination] = [bound, temporary_name].freeze
      open_handles << temporary
    end
    begin
      temporary.chmod(output_mode)
      operation_hook&.call(:before_stage_write, destination)
      temporary.write(contents.fetch(format))
      temporary.flush
      temporary.fsync
    ensure
      temporary.close unless temporary.closed?
    end
    bound.verify!
  end

  staged.each do |destination, (bound, _temporary_name)|
    operation_hook&.call(:before_backup_open, destination)
    source = nil
    Thread.handle_interrupt(State::DEFERRED_PUBLICATION_EXCEPTIONS) do
      source = begin
        bound.open_regular(destination.basename.to_s)
      rescue Errno::ENOENT
        nil
      end
      open_handles << source if source
    end
    unless source
      backups[destination] = nil
      next
    end

    backup_name = nil
    backup = nil
    Thread.handle_interrupt(State::DEFERRED_PUBLICATION_EXCEPTIONS) do
      backup_name, backup = bound.create_temporary(destination.basename.to_s, ".bak")
      backups[destination] = [bound, backup_name].freeze
      open_handles << backup
    end
    begin
      backup.chmod(source.stat.mode & 0o7777)
      operation_hook&.call(:before_backup_copy, destination)
      IO.copy_stream(source, backup)
      backup.flush
      backup.fsync
    ensure
      source.close
      backup.close
    end
    bound.verify!
  end
  before_commit&.call
  bound_directories.each_value(&:verify!)
  staged.each do |destination, (bound, temporary_name)|
    operation_hook&.call(:before_rename, destination)
    if rename
      Thread.handle_interrupt(State::DEFERRED_PUBLICATION_EXCEPTIONS) do
        committed << destination
        rename.call(bound.display_path(temporary_name), destination)
        bound.rename(temporary_name, destination.basename.to_s) if bound.regular_entry?(temporary_name)
      end
    else
      Thread.handle_interrupt(State::DEFERRED_PUBLICATION_EXCEPTIONS) do
        bound.rename(temporary_name, destination.basename.to_s)
        committed << destination
      end
    end
    operation_hook&.call(:after_rename, destination)
    bound.verify!
  end
  bound_directories.each_value(&:fsync)
  bound_directories.each_value(&:verify!)
rescue Exception => e # rubocop:disable Lint/RescueException -- rollback must include interrupts
  failed = true
  rollback_errors = []
  committed.reverse_each do |destination|
    backup = backups[destination]
    bound, backup_name = backup
    bound ||= staged.fetch(destination).first
    begin
      Thread.handle_interrupt(State::DEFERRED_PUBLICATION_EXCEPTIONS) do
        bound.unlink(destination.basename.to_s, missing_ok: true)
        bound.rename(backup_name, destination.basename.to_s) if backup_name
      end
    rescue SystemCallError, TranscriptionRuntimeError => rollback_error
      preserved_backups[backup] = true if backup_name
      rollback_errors << "#{destination}: #{rollback_error.message}"
    end
  end
  begin
    bound_directories&.each_value(&:fsync)
  rescue SystemCallError, TranscriptionRuntimeError => rollback_error
    rollback_errors << "directory sync: #{rollback_error.message}"
  end
  if rollback_errors.any?
    detail = rollback_errors.join("; ")
    retained = preserved_backups.keys.filter_map do |backup|
      backup&.then { |bound, name| bound.display_path(name).to_s }
    end.sort
    raise TranscriptionRuntimeError,
          "Output commit failed and rollback was incomplete (#{detail}); " \
          "preserved backups: #{retained}",
          cause: e
  end
  raise e
ensure
  cleanup_errors = []
  staged&.each_value do |bound, name|
    bound.unlink(name, missing_ok: true)
  rescue SystemCallError, TranscriptionRuntimeError => e
    cleanup_errors << e
  end
  backups&.each_value do |backup|
    next unless backup && !preserved_backups&.key?(backup)

    bound, name = backup
    bound.unlink(name, missing_ok: true)
  rescue SystemCallError, TranscriptionRuntimeError => e
    cleanup_errors << e
  end
  open_handles&.each { |handle| handle.close unless handle.closed? }
  bound_directories&.each_value(&:close)
  raise cleanup_errors.first if cleanup_errors.any? && !failed
end

.bind_profile_path(path) ⇒ Object



318
319
320
321
322
323
324
325
# File 'lib/cohere/transcribe/output/publication.rb', line 318

def bind_profile_path(path)
  return unless path

  destination = Pathname(path).expand_path
  State.ensure_bound_directory(destination.dirname)
rescue SystemCallError, ArgumentError, TranscriptionRuntimeError => e
  raise TranscriptionInputError, "Cannot prepare profile output path #{path}: #{e.message}"
end

.implementation_payloadObject



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/cohere/transcribe/output/publication.rb', line 526

def implementation_payload
  @implementation_payload ||= begin
    behavior_root = Pathname(__dir__).parent
    package_root = behavior_root.parent.parent
    suffixes = %w[.rb .onnx .so .bundle .dylib .dll]
    artifacts = Dir.glob(behavior_root.join("**", "*").to_s).filter_map do |name|
      path = Pathname(name)
      next unless path.file? && suffixes.include?(path.extname)

      [path.relative_path_from(package_root).to_s.tr(File::SEPARATOR, "/"), Digest::SHA256.file(path).hexdigest]
    end.to_h
    artifacts.each do |key, value|
      key.freeze
      value.freeze
    end
    artifacts.freeze
    {
      "package_version" => VERSION,
      "artifacts_sha256" => artifacts
    }.freeze
  end
end

.plan(entries, options) ⇒ Object



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
# File 'lib/cohere/transcribe/output/publication.rb', line 42

def plan(entries, options)
  publication = options.publication
  unless publication
    return entries.to_h do |entry|
      [
        entry.path,
        PublicationPlan.new(
          paths: {}.freeze,
          state_path: nil,
          checkpoint_path: nil,
          source_snapshot: nil,
          asr_contract_key: nil,
          render_contract_key: nil,
          lock_target: nil,
          directory_bindings: [].freeze,
          skipped: false,
          generation_id: nil
        )
      ]
    end.freeze
  end

  root = publication.output_dir&.expand_path
  if root
    root_binding = State.ensure_bound_directory(root)
    root = root_binding.canonical_path
  end

  claimed = {}
  input_paths = entries.to_h { |entry| [entry.path.expand_path.to_s, true] }
  profile_path = publication.profile_json&.expand_path
  profile_key = nil
  if profile_path
    if profile_path.symlink? || (profile_path.exist? && !profile_path.file?)
      raise TranscriptionInputError, "Profile path is not a regular file: #{profile_path}"
    end

    profile_key = prospective_realpath(profile_path).to_s
    if input_paths.key?(profile_key)
      raise TranscriptionInputError, "Profile path collides with an input audio file: #{profile_path}"
    end
  end
  asr_contract_key = State.asr_contract_key(options)
  render_contract_key = State.render_contract_key(options)
  plans = entries.to_h do |entry|
    source_snapshot = source_record(entry.path)
    parent = root ? root.join(entry.relative_path.dirname) : entry.path.dirname
    ensure_within_output_root!(prospective_realpath(parent), root, parent) if root
    parent_binding = State.ensure_bound_directory(parent, root_binding: root_binding)
    parent = parent_binding.canonical_path
    ensure_within_output_root!(parent, root, parent) if root
    directory_bindings = [root_binding, parent_binding].compact.uniq.freeze
    stem = entry.relative_path.basename(entry.relative_path.extname).to_s
    paths = publication.formats.to_h do |format|
      output_path = parent.join("#{stem}.#{format}")
      validate_output_path!(output_path, input_paths, entry.path)
      canonical = output_path.expand_path.to_s
      if (previous = claimed[canonical]) && previous != entry.path
        raise TranscriptionInputError,
              "Output collision between #{previous} and #{entry.path}: #{output_path}"
      end
      if profile_key == canonical
        raise TranscriptionInputError,
              "Profile path collides with a transcript output: #{output_path}"
      end
      claimed[canonical] = entry.path
      [format, output_path.freeze]
    end.freeze
    state_path = State.state_path_for_outputs(paths)
    checkpoint_path = State.checkpoint_path_for_outputs(paths)
    lock_target = State.lock_target_for_outputs(paths)
    {
      "State marker" => state_path,
      "ASR checkpoint" => checkpoint_path
    }.each do |label, reserved_path|
      if reserved_path.symlink? || (reserved_path.exist? && !reserved_path.file?)
        raise TranscriptionInputError, "#{label} is not a regular file: #{reserved_path}"
      end

      reserved_key = reserved_path.expand_path.to_s
      if profile_key == reserved_key
        raise TranscriptionInputError,
              "Profile path collides with a reserved #{label.downcase}: #{reserved_path}"
      end
      if input_paths.key?(reserved_key) || claimed.key?(reserved_key)
        raise TranscriptionInputError, "#{label} collides with an input or output: #{reserved_path}"
      end

      claimed[reserved_key] = entry.path
    end

    existing = paths.values.select(&:exist?)
    if existing.any? && publication.existing == "error"
      rendered = existing.map { |path| "  #{path}" }.join("\n")
      raise TranscriptionInputError,
            "Output already exists:\n#{rendered}\n" \
            "Use existing: 'overwrite' or existing: 'skip'."
    end
    verification = if publication.existing == "skip" && existing.length == paths.length
                     State.verify_published_outputs(
                       source_snapshot: source_snapshot,
                       output_paths: paths,
                       state_path: state_path,
                       asr_contract_key: asr_contract_key,
                       render_contract_key: render_contract_key,
                       directory_binding: directory_bindings.last,
                       guard_bindings: directory_bindings
                     )
                   end
    skipped = verification&.verified? || false
    [
      entry.path,
      PublicationPlan.new(
        paths: paths,
        state_path: state_path.freeze,
        checkpoint_path: checkpoint_path.freeze,
        source_snapshot: source_snapshot,
        asr_contract_key: asr_contract_key,
        render_contract_key: render_contract_key,
        lock_target: lock_target,
        directory_bindings: directory_bindings,
        skipped: skipped,
        generation_id: verification&.generation_id
      )
    ]
  end
  plans.freeze
rescue SystemCallError, ArgumentError, TranscriptionRuntimeError => e
  detail = e.message.to_s.delete("\0")
  raise TranscriptionInputError, "Cannot prepare output paths: #{detail}"
end

.profile_payload(run, runtime_metrics: nil) ⇒ Object



327
328
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/cohere/transcribe/output/publication.rb', line 327

def profile_payload(run, runtime_metrics: nil)
  requested = run.requested_options
  resolved = run.resolved_options
  statistics = run.statistics
  runtime_metrics ||= {}
  file_segmentation = runtime_metrics.fetch(:file_segmentation, {})
  results = run.results
  successful = results.reject { |result| result.status == "failed" }
  representative = results.find { |result| result.provenance.model_id } || results.first
  all_durations = results.flat_map do |result|
    profile_segment_durations(result, file_segmentation[result.path.to_s])
  end
  inferred_durations = results.reject do |result|
    result.provenance.resumed_from_asr_checkpoint
  end.flat_map do |result|
    profile_segment_durations(result, file_segmentation[result.path.to_s])
  end
  requested_engines = results.filter_map(&:provenance)
                             .filter_map(&:vad_engine_requested).uniq.sort
  actual_engines = results.filter_map(&:provenance)
                          .filter_map(&:vad_engine_actual).uniq.sort
  vad_prepared_groups = runtime_metrics.fetch(:vad_prepared_groups, 0)
  vad_model_calls = runtime_metrics.fetch(:vad_model_calls, 0)
  vad_valid_frames = runtime_metrics.fetch(:vad_valid_frames, 0)
  vad_padded_frames = runtime_metrics.fetch(:vad_padded_frames, 0)
  vad_max_files_per_call = runtime_metrics.fetch(:vad_max_files_per_call, 0)
  vad_effective_block_frames = runtime_metrics.fetch(:vad_effective_block_frames, 0)
  vad_intraop_threads = runtime_metrics.fetch(:vad_intraop_threads, 0)
  vad_padding_ratio = if vad_padded_frames.zero?
                        0.0
                      else
                        1.0 - vad_valid_frames.fdiv(vad_padded_frames)
                      end

  {
    "schema_version" => PROFILE_SCHEMA_VERSION,
    "created_unix_seconds" => Time.now.to_f,
    "implementation" => implementation_payload,
    "models" => profile_models_payload(representative, resolved),
    "environment" => environment_payload(resolved, runtime_metrics),
    "configuration" => configuration_payload(requested, results, resolved: false),
    "resolved_configuration" => configuration_payload(resolved, results, resolved: true),
    "run" => {
      "elapsed_seconds" => statistics.elapsed_seconds,
      "successful_files" => successful.length,
      "failed_files" => results.count { |result| result.status == "failed" },
      "successful_audio_seconds" => statistics.successful_audio_seconds,
      "real_time_factor_x" => statistics.real_time_factor_x
    },
    "timings" => timings_payload(statistics, runtime_metrics),
    "vad" => {
      "requested_engines" => requested_engines,
      "actual_engines" => actual_engines,
      "torch_device" => vad_prepared_groups.positive? ? "cpu" : nil,
      # This reference-schema field reports the effective CPU
      # intra-op count for Ruby's sequence-ONNX substitution.
      "torch_intraop_threads" => vad_intraop_threads.positive? ? vad_intraop_threads : nil,
      "configured_file_batch_size" => resolved.vad_batch_size,
      "configured_block_frames" => resolved.vad_block_frames,
      "effective_block_frames" => vad_effective_block_frames.positive? ? vad_effective_block_frames : nil,
      "prepared_groups" => vad_prepared_groups,
      "model_calls" => vad_model_calls,
      "valid_frames" => vad_valid_frames,
      "padded_frames" => vad_padded_frames,
      "padding_ratio" => vad_padding_ratio,
      "max_files_per_call" => vad_max_files_per_call
    },
    "asr" => {
      "batches" => statistics.asr_batches,
      "processor_rows" => statistics.asr_processor_rows,
      "generated_tokens" => statistics.generated_tokens,
      "valid_feature_frames" => nil,
      "padded_feature_frames" => nil,
      "discarded_processor_rows" => 0,
      "discarded_valid_feature_frames" => 0,
      "discarded_padded_feature_frames" => 0,
      "padding_ratio" => nil,
      "effective_batch_min" => runtime_metrics[:effective_batch_min],
      "effective_batch_max" => runtime_metrics[:effective_batch_max],
      "final_batch_size" => runtime_metrics[:final_batch_size],
      "final_batch_cap" => runtime_metrics[:final_batch_cap],
      "oom_retries" => statistics.oom_retries,
      "truncation_retries" => statistics.truncation_retries,
      "discarded_feature_batches" => 0,
      "pin_memory_fallbacks" => 0,
      "all_segment_duration_seconds" => duration_quantiles(all_durations),
      "inferred_segment_duration_seconds" => duration_quantiles(inferred_durations),
      "batch_history" => profile_batch_history(runtime_metrics[:batch_history]),
      "checkpoint_resumed_files" => results.count do |result|
        result.provenance.resumed_from_asr_checkpoint
      end,
      "checkpoint_written_files" => runtime_metrics.fetch(:checkpoint_written_files, 0)
    },
    "cuda_memory" => {
      "total_gib" => runtime_metrics[:cuda_total_gib],
      "free_start_gib" => runtime_metrics[:cuda_free_start_gib],
      "free_end_gib" => runtime_metrics[:cuda_free_end_gib],
      "peak_allocated_gib" => nil,
      "peak_reserved_gib" => nil
    },
    "files" => results.map do |result|
      profile_file_payload(
        result,
        resolved,
        segmentation: file_segmentation[result.path.to_s]
      )
    end
  }
end

.render(format, result, options, speech_spans: nil) ⇒ Object



437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/cohere/transcribe/output/publication.rb', line 437

def render(format, result, options, speech_spans: nil)
  case format
  when "txt"
    lines = result.segments.empty? ? [result.text.to_s] : result.segments.map(&:text)
    Rendering.plain_text(lines)
  when "srt" then Rendering.srt(result.cues)
  when "vtt" then Rendering.vtt(result.cues)
  when "json" then Rendering.json(result_payload(result, options, speech_spans: speech_spans))
  else
    raise TranscriptionRuntimeError, "Unsupported publication format: #{format.inspect}"
  end
end

.result_payload(result, options, speech_spans: nil) ⇒ Object



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/cohere/transcribe/output/publication.rb', line 450

def result_payload(result, options, speech_spans: nil)
  provenance = result.provenance
  {
    "schema_version" => OUTPUT_SCHEMA_VERSION,
    "implementation" => implementation_payload,
    "source" => {
      "path" => result.path.to_s,
      "duration_seconds" => result.duration,
      "sample_rate" => SAMPLE_RATE,
      "decode_backend" => provenance.decode_backend,
      "decode_fallback_reason" => provenance.decode_fallback_reason
    },
    "language" => options.language,
    "segmentation" => options.vad,
    "segmentation_details" => {
      "mode" => options.vad,
      "requested_engine" => provenance.vad_engine_requested,
      "actual_engine" => provenance.vad_engine_actual,
      "provider" => provenance.vad_provider,
      "provider_options" => vad_provider_options(provenance, options),
      "fallback_reason" => provenance.vad_fallback_reason,
      "merge" => options.vad_merge,
      "parameters" => segmentation_parameters(options),
      "speech_spans" => speech_spans_payload(result, speech_spans)
    },
    "timing" => options.alignment,
    "models" => {
      "asr" => {
        "id" => provenance.model_id,
        "revision" => provenance.model_revision,
        "format" => provenance.model_format,
        "quantization" => nil,
        "adapter" => provenance.adapter_id && {
          "id" => provenance.adapter_id,
          "revision" => provenance.adapter_revision
        }
      },
      "vad" => output_vad_model_payload(options, provenance),
      "aligner" => aligner_payload(options)
    },
    "fallback_alignment_segments" => provenance.fallback_alignment_segments,
    "repetition_detector_version" => REPETITION_DETECTOR_VERSION,
    "repetition_stopped_segments" => provenance.repetition_stopped_segments,
    "truncation_retried_segments" => provenance.truncation_retried_segments,
    "token_limit_segments" => provenance.token_limit_segments,
    "generated_tokens_by_segment" => provenance.generated_tokens_by_segment.map do |index, tokens|
      { "segment_index" => index, "tokens" => tokens }
    end,
    "transcript" => transcript_lines(result),
    "segments" => result.segments.filter_map do |segment|
      text = PythonText.strip(segment.text.to_s)
      next if text.empty?

      {
        "segment_index" => segment.index,
        "start" => segment.start,
        "end" => segment.end,
        "text" => text
      }
    end,
    "words" => result.words.map do |word|
      {
        "start" => word.start,
        "end" => word.end,
        "text" => word.text,
        "segment_index" => word.segment_index,
        "segment_word_index" => word.segment_word_index,
        "timing_source" => word.timing_source
      }
    end,
    "cues" => result.cues.map do |cue|
      { "start" => cue.start, "end" => cue.end, "text" => cue.text }
    end
  }
end

.revalidate(plan, options) ⇒ Object



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
# File 'lib/cohere/transcribe/output/publication.rb', line 206

def revalidate(plan, options)
  return PublicationDecision.new(action: :process, checkpoint: nil, generation_id: nil, reason: nil) if plan.paths.empty?

  plan.directory_bindings.each(&:verify!)
  State.ensure_source_unchanged!(plan.source_snapshot)
  validate_reserved_path!(plan.state_path, "State marker")
  validate_reserved_path!(plan.checkpoint_path, "ASR checkpoint")
  plan.paths.each_value { |path| validate_runtime_output_path!(path) }
  existing = plan.paths.values.select(&:exist?)
  if existing.any? && options.publication.existing == "error"
    rendered = existing.map { |path| "  #{path}" }.join("\n")
    raise TranscriptionInputError,
          "Output already exists:\n#{rendered}\n" \
          "Use existing: 'overwrite' or existing: 'skip'."
  end

  if options.publication.existing == "skip" && existing.length == plan.paths.length
    verification = State.verify_published_outputs(
      source_snapshot: plan.source_snapshot,
      output_paths: plan.paths,
      state_path: plan.state_path,
      asr_contract_key: plan.asr_contract_key,
      render_contract_key: plan.render_contract_key,
      directory_binding: plan.directory_bindings.last,
      guard_bindings: plan.directory_bindings
    )
    if verification.verified?
      return PublicationDecision.new(
        action: :skip,
        checkpoint: nil,
        generation_id: verification.generation_id,
        reason: nil
      )
    end
    publication_reason = verification.reason
  elsif existing.any? && options.publication.existing == "skip"
    publication_reason = "requested output set is incomplete"
  end

  checkpoint = State.restore_asr_checkpoint(
    path: plan.checkpoint_path,
    source_snapshot: plan.source_snapshot,
    asr_contract_key: plan.asr_contract_key,
    directory_binding: plan.directory_bindings.last,
    guard_bindings: plan.directory_bindings
  )
  if checkpoint.restored?
    return PublicationDecision.new(
      action: :resume,
      checkpoint: checkpoint.checkpoint,
      generation_id: checkpoint.checkpoint.generation_id,
      reason: publication_reason
    )
  end

  reasons = [publication_reason, checkpoint.reason].compact
  PublicationDecision.new(
    action: :process,
    checkpoint: nil,
    generation_id: nil,
    reason: reasons.empty? ? nil : reasons.join("; ").freeze
  )
ensure
  plan.directory_bindings.each(&:verify!) if plan&.paths&.any?
end

.verify_plan_directory_continuity!(before_plans, after_plans) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/cohere/transcribe/output/publication.rb', line 180

def verify_plan_directory_continuity!(before_plans, after_plans)
  raise TranscriptionRuntimeError, "Publication inputs changed between planning passes" unless before_plans.keys == after_plans.keys

  before_plans.each do |path, before_plan|
    after_plan = after_plans.fetch(path)
    before_plan.directory_bindings.each(&:verify!)
    after_plan.directory_bindings.each(&:verify!)
    next if before_plan.directory_bindings == after_plan.directory_bindings

    raise TranscriptionRuntimeError,
          "Publication parent identity changed between planning passes: #{path}"
  end
  nil
end

.verify_profile_directory_continuity!(before_binding, after_binding) ⇒ Object



195
196
197
198
199
200
201
202
203
204
# File 'lib/cohere/transcribe/output/publication.rb', line 195

def verify_profile_directory_continuity!(before_binding, after_binding)
  return if before_binding.nil? && after_binding.nil?

  before_binding&.verify!
  after_binding&.verify!
  return if before_binding == after_binding

  raise TranscriptionRuntimeError,
        "Profile parent identity changed between planning passes"
end

.with_plan_lock(plan, &block) ⇒ Object



174
175
176
177
178
# File 'lib/cohere/transcribe/output/publication.rb', line 174

def with_plan_lock(plan, &block)
  return block.call unless plan.lock_target

  State.with_output_lock(plan.lock_target, &block)
end

.write(plan, result, options, generation_id: nil, speech_spans: nil) ⇒ Object



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
# File 'lib/cohere/transcribe/output/publication.rb', line 272

def write(plan, result, options, generation_id: nil, speech_spans: nil)
  return [].freeze if plan.paths.empty?

  contents = plan.paths.to_h do |format, _path|
    [format, render(format, result, options, speech_spans: speech_spans)]
  end
  snapshot = plan.source_snapshot || source_record(result.path)
  generation_id = SecureRandom.hex(16) if generation_id.to_s.empty?
  manifest = State.published_manifest_content(
    source_snapshot: snapshot,
    output_paths: plan.paths,
    contents: contents,
    asr_contract_key: plan.asr_contract_key || State.asr_contract_key(options),
    render_contract_key: plan.render_contract_key || State.render_contract_key(options),
    generation_id: generation_id
  )
  transaction_paths = plan.paths.merge("__manifest__" => plan.state_path).freeze
  transaction_contents = contents.merge("__manifest__" => manifest).freeze
  atomic_write_set(
    transaction_paths,
    transaction_contents,
    before_commit: -> { State.ensure_source_unchanged!(snapshot) },
    directory_bindings: plan.directory_bindings
  )
  plan.paths.values.freeze
end

.write_profile(path, run, runtime_metrics: nil, directory_binding: nil) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/cohere/transcribe/output/publication.rb', line 299

def write_profile(path, run, runtime_metrics: nil, directory_binding: nil)
  return unless path

  destination = Pathname(path).expand_path
  directory_binding ||= State.ensure_bound_directory(destination.dirname)
  payload = profile_payload(run, runtime_metrics: runtime_metrics)
  atomic_write_set(
    { "json" => destination },
    { "json" => Rendering.json(payload) },
    directory_bindings: [directory_binding]
  )
  destination
rescue Interrupt, SystemExit
  raise
rescue StandardError => e
  raise TranscriptionRuntimeError,
        "profile output failed: #{e.class}: Cannot write #{path}: #{e.message}"
end