| | | 1 | | using System.Text.Json; |
| | | 2 | | using EHonda.KicktippAi.Core; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Orchestrator.Commands.Observability.Experiments; |
| | | 5 | | using Orchestrator.Commands.Observability.ExportExperimentDataset; |
| | | 6 | | using Orchestrator.Infrastructure.Factories; |
| | | 7 | | using Spectre.Console; |
| | | 8 | | using Spectre.Console.Cli; |
| | | 9 | | |
| | | 10 | | namespace Orchestrator.Commands.Observability.PrepareRepeatedMatch; |
| | | 11 | | |
| | | 12 | | public sealed class PrepareRepeatedMatchCommand : AsyncCommand<PrepareRepeatedMatchSettings> |
| | | 13 | | { |
| | | 14 | | private readonly IAnsiConsole _console; |
| | | 15 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 16 | | private readonly ILogger<PrepareRepeatedMatchCommand> _logger; |
| | | 17 | | |
| | 1 | 18 | | public PrepareRepeatedMatchCommand( |
| | 1 | 19 | | IAnsiConsole console, |
| | 1 | 20 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 1 | 21 | | ILogger<PrepareRepeatedMatchCommand> logger) |
| | | 22 | | { |
| | 1 | 23 | | _console = console; |
| | 1 | 24 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 1 | 25 | | _logger = logger; |
| | 1 | 26 | | } |
| | | 27 | | |
| | | 28 | | protected override async Task<int> ExecuteAsync(CommandContext context, PrepareRepeatedMatchSettings settings, Cance |
| | | 29 | | { |
| | | 30 | | try |
| | | 31 | | { |
| | 1 | 32 | | var matchOutcomeRepository = _firebaseServiceFactory.CreateMatchOutcomeRepository(); |
| | 1 | 33 | | var outcome = await LoadCompletedOutcomeAsync(matchOutcomeRepository, settings, cancellationToken); |
| | 1 | 34 | | var sourceDatasetName = ExperimentArtifactSupport.BuildSourceDatasetName(settings.CommunityContext); |
| | 1 | 35 | | var sourceItem = ExperimentArtifactSupport.BuildHostedDatasetItem(outcome); |
| | 1 | 36 | | var sliceKey = string.IsNullOrWhiteSpace(settings.SliceKey) |
| | 1 | 37 | | ? $"repeat-{settings.SampleSize}" |
| | 1 | 38 | | : settings.SliceKey.Trim(); |
| | 1 | 39 | | var sourcePoolKey = string.IsNullOrWhiteSpace(settings.SourcePoolKey) |
| | 1 | 40 | | ? ExperimentArtifactSupport.BuildRepeatedMatchSourcePoolKey(settings.Matchday!.Value, settings.HomeTeam, |
| | 1 | 41 | | : settings.SourcePoolKey.Trim(); |
| | 1 | 42 | | var datasetName = settings.DatasetName |
| | 1 | 43 | | ?? $"{sourceDatasetName}/repeated-match/{sourcePoolKey}/{sliceKey}"; |
| | 1 | 44 | | var datasetDescription = string.IsNullOrWhiteSpace(settings.DatasetDescription) |
| | 1 | 45 | | ? null |
| | 1 | 46 | | : settings.DatasetDescription.Trim(); |
| | 1 | 47 | | var outputDirectory = ResolveOutputDirectory(settings.OutputDirectory, settings.CommunityContext, sourcePool |
| | 1 | 48 | | var sliceArtifactPath = Path.Combine(outputDirectory, "slice-dataset.json"); |
| | 1 | 49 | | var sliceManifestPath = Path.Combine(outputDirectory, "slice-manifest.json"); |
| | | 50 | | |
| | 1 | 51 | | Directory.CreateDirectory(outputDirectory); |
| | | 52 | | |
| | 1 | 53 | | var startsAt = GetStartsAt(sourceItem); |
| | 1 | 54 | | var sourceItems = Enumerable.Range(1, settings.SampleSize) |
| | 1 | 55 | | .Select(index => |
| | 1 | 56 | | { |
| | 1 | 57 | | var sliceDatasetItemId = ExperimentArtifactSupport.BuildRepeatedSliceDatasetItemId( |
| | 1 | 58 | | sourceItem.Id, |
| | 1 | 59 | | sliceKey, |
| | 1 | 60 | | index, |
| | 1 | 61 | | settings.SampleSize); |
| | 1 | 62 | | |
| | 1 | 63 | | return new PreparedExperimentSourceItem( |
| | 1 | 64 | | sourceItem.Id, |
| | 1 | 65 | | sliceDatasetItemId, |
| | 1 | 66 | | sourceItem.Id, |
| | 1 | 67 | | sourceItem.Metadata.Competition, |
| | 1 | 68 | | sourceItem.Metadata.Season, |
| | 1 | 69 | | sourceItem.Metadata.CommunityContext, |
| | 1 | 70 | | sourceItem.Metadata.Matchday, |
| | 1 | 71 | | sourceItem.Metadata.MatchdayLabel, |
| | 1 | 72 | | sourceItem.Metadata.HomeTeam, |
| | 1 | 73 | | sourceItem.Metadata.AwayTeam, |
| | 1 | 74 | | startsAt, |
| | 1 | 75 | | sourceItem.Metadata.TippSpielId, |
| | 1 | 76 | | sourceItem.ExpectedOutput.HomeGoals, |
| | 1 | 77 | | sourceItem.ExpectedOutput.AwayGoals); |
| | 1 | 78 | | }) |
| | 1 | 79 | | .ToList(); |
| | | 80 | | |
| | 1 | 81 | | var bundle = PreparedExperimentBundleBuilder.Build( |
| | 1 | 82 | | sourceItems, |
| | 1 | 83 | | settings.CommunityContext, |
| | 1 | 84 | | sourceDatasetName, |
| | 1 | 85 | | datasetName, |
| | 1 | 86 | | sliceKey, |
| | 1 | 87 | | "repeated-match", |
| | 1 | 88 | | "repeated-match", |
| | 1 | 89 | | sourcePoolKey, |
| | 1 | 90 | | null, |
| | 1 | 91 | | datasetDescription, |
| | 1 | 92 | | BuildRepeatedMatchDatasetMetadata(sourceItem, settings.SampleSize, datasetDescription)); |
| | | 93 | | |
| | 1 | 94 | | await WriteJsonFileAsync(sliceArtifactPath, bundle.Artifact, cancellationToken); |
| | 1 | 95 | | await WriteJsonFileAsync(sliceManifestPath, bundle.Manifest, cancellationToken); |
| | | 96 | | |
| | 1 | 97 | | var summary = new |
| | 1 | 98 | | { |
| | 1 | 99 | | mode = "repeated-match", |
| | 1 | 100 | | settings.CommunityContext, |
| | 1 | 101 | | datasetName = bundle.Manifest.SliceDatasetName, |
| | 1 | 102 | | bundle.Manifest.SourceDatasetName, |
| | 1 | 103 | | bundle.Manifest.SourcePoolKey, |
| | 1 | 104 | | bundle.Manifest.SliceKey, |
| | 1 | 105 | | bundle.Manifest.SampleSize, |
| | 1 | 106 | | settings.HomeTeam, |
| | 1 | 107 | | settings.AwayTeam, |
| | 1 | 108 | | Matchday = settings.Matchday, |
| | 1 | 109 | | datasetDescription = bundle.Artifact.DatasetDescription, |
| | 1 | 110 | | datasetMetadata = bundle.Artifact.DatasetMetadata, |
| | 1 | 111 | | bundle.Manifest.SelectedItemIds, |
| | 1 | 112 | | bundle.Manifest.SelectedItemIdsHash, |
| | 1 | 113 | | outputDirectory, |
| | 1 | 114 | | sliceArtifactPath, |
| | 1 | 115 | | sliceManifestPath |
| | 1 | 116 | | }; |
| | | 117 | | |
| | 1 | 118 | | _console.WriteLine(JsonSerializer.Serialize(summary, PreparedExperimentCommandSupport.JsonOptions)); |
| | 1 | 119 | | return 0; |
| | | 120 | | } |
| | 0 | 121 | | catch (Exception ex) |
| | | 122 | | { |
| | 0 | 123 | | _logger.LogError(ex, "Error preparing repeated-match experiment artifact"); |
| | 0 | 124 | | _console.MarkupLine($"[red]Error:[/] {Markup.Escape(ex.Message)}"); |
| | 0 | 125 | | return 1; |
| | | 126 | | } |
| | 1 | 127 | | } |
| | | 128 | | |
| | | 129 | | private static IReadOnlyDictionary<string, object?> BuildRepeatedMatchDatasetMetadata( |
| | | 130 | | HostedMatchExperimentDatasetItem sourceItem, |
| | | 131 | | int repetitionCount, |
| | | 132 | | string? datasetDescription) |
| | | 133 | | { |
| | 1 | 134 | | var actualResult = $"{sourceItem.ExpectedOutput.HomeGoals}:{sourceItem.ExpectedOutput.AwayGoals}"; |
| | 1 | 135 | | var actualResultDisplay = $"{sourceItem.Metadata.HomeTeam} {sourceItem.ExpectedOutput.HomeGoals} - {sourceItem.E |
| | 1 | 136 | | var metadata = new Dictionary<string, object?> |
| | 1 | 137 | | { |
| | 1 | 138 | | ["fixture"] = $"{sourceItem.Metadata.HomeTeam} vs {sourceItem.Metadata.AwayTeam}", |
| | 1 | 139 | | ["actualResult"] = actualResult, |
| | 1 | 140 | | ["actualResultDisplay"] = actualResultDisplay, |
| | 1 | 141 | | ["matchday"] = sourceItem.Metadata.Matchday, |
| | 1 | 142 | | ["repetitionCount"] = repetitionCount |
| | 1 | 143 | | }; |
| | | 144 | | |
| | 1 | 145 | | if (!string.IsNullOrWhiteSpace(datasetDescription)) |
| | | 146 | | { |
| | 1 | 147 | | metadata["datasetDescription"] = datasetDescription; |
| | 1 | 148 | | metadata["interestingBecause"] = datasetDescription; |
| | | 149 | | } |
| | | 150 | | |
| | 1 | 151 | | return metadata; |
| | | 152 | | } |
| | | 153 | | |
| | | 154 | | private static string GetStartsAt(HostedMatchExperimentDatasetItem item) |
| | | 155 | | { |
| | 1 | 156 | | if (item.Input.ValueKind != JsonValueKind.Object |
| | 1 | 157 | | || !item.Input.TryGetProperty("startsAt", out var startsAt) |
| | 1 | 158 | | || startsAt.ValueKind != JsonValueKind.String |
| | 1 | 159 | | || string.IsNullOrWhiteSpace(startsAt.GetString())) |
| | | 160 | | { |
| | 0 | 161 | | throw new InvalidOperationException($"Dataset item '{item.Id}' is missing input.startsAt."); |
| | | 162 | | } |
| | | 163 | | |
| | 1 | 164 | | return startsAt.GetString()!; |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | private static async Task<PersistedMatchOutcome> LoadCompletedOutcomeAsync( |
| | | 168 | | IMatchOutcomeRepository matchOutcomeRepository, |
| | | 169 | | PrepareRepeatedMatchSettings settings, |
| | | 170 | | CancellationToken cancellationToken) |
| | | 171 | | { |
| | 1 | 172 | | var outcomes = await matchOutcomeRepository.GetMatchdayOutcomesAsync( |
| | 1 | 173 | | settings.Matchday!.Value, |
| | 1 | 174 | | settings.CommunityContext, |
| | 1 | 175 | | cancellationToken); |
| | | 176 | | |
| | 1 | 177 | | var outcome = outcomes.FirstOrDefault(candidate => |
| | 1 | 178 | | string.Equals(candidate.HomeTeam, settings.HomeTeam, StringComparison.OrdinalIgnoreCase) |
| | 1 | 179 | | && string.Equals(candidate.AwayTeam, settings.AwayTeam, StringComparison.OrdinalIgnoreCase)); |
| | | 180 | | |
| | 1 | 181 | | if (outcome is null) |
| | | 182 | | { |
| | 0 | 183 | | throw new InvalidOperationException( |
| | 0 | 184 | | $"No persisted match outcome was found for {settings.HomeTeam} vs {settings.AwayTeam} on matchday {setti |
| | | 185 | | } |
| | | 186 | | |
| | 1 | 187 | | if (!outcome.HasOutcome || outcome.HomeGoals is null || outcome.AwayGoals is null) |
| | | 188 | | { |
| | 0 | 189 | | throw new InvalidOperationException( |
| | 0 | 190 | | $"The selected match does not have a completed persisted outcome yet: {settings.HomeTeam} vs {settings.A |
| | | 191 | | } |
| | | 192 | | |
| | 1 | 193 | | return outcome; |
| | 1 | 194 | | } |
| | | 195 | | |
| | | 196 | | private static string ResolveOutputDirectory( |
| | | 197 | | string? outputDirectoryOverride, |
| | | 198 | | string communityContext, |
| | | 199 | | string sourcePoolKey, |
| | | 200 | | string sliceKey) |
| | | 201 | | { |
| | 1 | 202 | | if (!string.IsNullOrWhiteSpace(outputDirectoryOverride)) |
| | | 203 | | { |
| | 1 | 204 | | return Path.GetFullPath(outputDirectoryOverride); |
| | | 205 | | } |
| | | 206 | | |
| | 0 | 207 | | return Path.GetFullPath(Path.Combine( |
| | 0 | 208 | | "artifacts", |
| | 0 | 209 | | "langfuse-experiments", |
| | 0 | 210 | | "repeated-match", |
| | 0 | 211 | | ExperimentArtifactSupport.Slugify(communityContext), |
| | 0 | 212 | | sourcePoolKey, |
| | 0 | 213 | | sliceKey)); |
| | | 214 | | } |
| | | 215 | | |
| | | 216 | | private static Task WriteJsonFileAsync<T>(string path, T value, CancellationToken cancellationToken) |
| | | 217 | | { |
| | 1 | 218 | | return File.WriteAllTextAsync(path, JsonSerializer.Serialize(value, PreparedExperimentCommandSupport.JsonOptions |
| | | 219 | | } |
| | | 220 | | } |