Files
Sprachmittler/Packages/SprachmittlerKit/Tests/SprachmittlerEvalTests/SprachmittlerEvalTests.swift
T
schihei 0ab5ae78bf feat(m7-m8): evaluation harness, privacy self-test, localisation and release
M7: corpus manifest loader/validation, chrF/BLEU/token/numeric metrics, raw-output and report.md/report.json writer, and sprachmittler-cli languages/detect/eval. A synthetic 4-segment run with the 7B validated the harness; the private-corpus and 1.8B evaluation and the default-model ADR remain open.

M8: privacy-check root fixture + seeded self-test wired into make verify; English/German localisation for the app shell; end-user USER_GUIDE; release.sh (unsigned archive, Developer ID sign, notarise/staple, DMG, --dry-run); idle CPU/memory and warm 7B measurements in PERFORMANCE.

Docs: PROGRESS M7–M8, MODEL_EVALUATION results log/gate status, PERFORMANCE measurements, TESTING evaluation cases, ADR-008 status. Compatibility/VoiceOver/notarisation gates remain manual.

Verified: make verify green (format, strict lint, privacy self-test, Debug+Release signatures, 227 package tests); CLI languages/detect/eval run; release dry-run.
2026-11-26 14:16:21 +01:00

276 lines
11 KiB
Swift

import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
import Testing
@testable import SprachmittlerEval
@Suite("Evaluation metrics")
struct EvaluationMetricsTests {
@Test func identicalTextScoresFullMarks() {
#expect(EvaluationMetrics.chrF(reference: "Hello world", hypothesis: "Hello world") == 100)
#expect(EvaluationMetrics.bleu(reference: "a b c d", hypothesis: "a b c d") == 100)
#expect(EvaluationMetrics.tokenRetention(source: "Hello", translation: "Hello") == 1)
#expect(EvaluationMetrics.numericConsistency(source: "1.5", translation: "1,5") == 1)
}
@Test func disjointTextScoresZero() {
#expect(EvaluationMetrics.chrF(reference: "abc", hypothesis: "xyz") == 0)
#expect(EvaluationMetrics.bleu(reference: "a b c d", hypothesis: "w x y z") == 0)
}
@Test func lostProtectedTokenIsCounted() {
let source = "Open https://example.com and use {{name}}."
#expect(
EvaluationMetrics.tokenRetention(
source: source,
translation: "Öffne https://example.com und nutze {{name}}."
) == 1
)
#expect(
EvaluationMetrics.tokenRetention(
source: source,
translation: "Öffne example.com und nutze name."
) == 0
)
}
@Test func localeNumbersAreNormalised() {
#expect(EvaluationMetrics.numericConsistency(source: "1.5 and 1 000", translation: "1,5 und 1000") == 1)
#expect(EvaluationMetrics.numericConsistency(source: "1.5", translation: "2.5") == 0)
}
}
@Suite("Manifest loading")
struct EvaluationManifestTests {
@Test func loadsRelativePathsAndFiltersTheTarget() throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
let manifest = directory.appendingPathComponent("corpus.json")
try writeText(
#"""
{
"version": 1,
"segments": [
{
"id": "seg-1",
"source": "source.txt",
"sourceLanguage": "en",
"targetLanguage": "de",
"category": "en-de-prose",
"reference": "reference.txt",
"referenceKind": "human"
}
]
}
"""#,
to: manifest
)
let resolved = try EvaluationManifestLoader.load(manifestURL: manifest, target: "de")
#expect(resolved.segments.count == 1)
#expect(resolved.segments[0].sourceText == "Hello.")
#expect(resolved.segments[0].referenceText == "Hallo.")
#expect(throws: ManifestError.noMatchingTarget("fr")) {
try EvaluationManifestLoader.load(manifestURL: manifest, target: "fr")
}
}
@Test func rejectsDuplicateIDsAndMissingFiles() throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("x", to: directory.appendingPathComponent("source.txt"))
try writeText("y", to: directory.appendingPathComponent("reference.txt"))
let manifest = directory.appendingPathComponent("corpus.json")
let duplicate = manifestJSON([
segmentJSON(id: "seg-1"),
segmentJSON(id: "seg-1"),
])
try writeText(duplicate, to: manifest)
#expect(throws: ManifestError.duplicateID("seg-1")) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
let missing = manifestJSON([
segmentJSON(id: "seg-1", source: "missing.txt"),
])
try writeText(missing, to: manifest)
#expect(throws: ManifestError.missingFile(directory.appendingPathComponent("missing.txt").path)) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
}
@Test func rejectsBadIDsAndReferenceKinds() throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("x", to: directory.appendingPathComponent("source.txt"))
try writeText("y", to: directory.appendingPathComponent("reference.txt"))
let manifest = directory.appendingPathComponent("corpus.json")
let badID = manifestJSON([
segmentJSON(id: "Bad ID"),
])
try writeText(badID, to: manifest)
#expect(throws: ManifestError.invalidID("Bad ID")) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
let badKind = manifestJSON([
segmentJSON(id: "seg-1", referenceKind: "machine"),
])
try writeText(badKind, to: manifest)
#expect(throws: ManifestError.invalidReferenceKind("machine")) {
try EvaluationManifestLoader.load(manifestURL: manifest)
}
}
}
@Suite("Evaluation runner and report")
struct EvaluationRunnerTests {
@Test func runsSegmentsWritesRawOutputsAndReports() async throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
let manifestURL = directory.appendingPathComponent("corpus.json")
try writeText(manifestJSON([segmentJSON(id: "seg-1")]), to: manifestURL)
let manifest = try EvaluationManifestLoader.load(manifestURL: manifestURL)
let output = directory.appendingPathComponent("results")
let configuration = EvaluationConfiguration(
models: ["test-model"],
runs: 1,
outputDirectory: output
)
let runner = EvaluationRunner(
manifest: manifest,
configuration: configuration,
environment: EvaluationEnvironment(
serverVersion: "0.40.18",
ollamaVersion: "0.40.18",
hardware: "Test",
macOS: "Test",
models: ["test-model": "abcdef"]
),
pipelineFactory: { _ in ImmediateStreaming(translation: "Hallo.") },
warmUp: { _ in },
unload: { _ in }
)
let report = try await runner.run()
#expect(report.models.count == 1)
#expect(report.models[0].categories.count == 1)
#expect(report.models[0].categories[0].failureRate == 0)
#expect(report.models[0].categories[0].chrF == 100)
#expect(FileManager.default.fileExists(atPath: output.appendingPathComponent("report.md").path))
#expect(FileManager.default.fileExists(atPath: output.appendingPathComponent("report.json").path))
#expect(FileManager.default.fileExists(
atPath: output.appendingPathComponent("test-model/seg-1-run0.txt").path
))
let markdown = try String(
contentsOf: output.appendingPathComponent("report.md"),
encoding: .utf8
)
#expect(markdown.contains("## Environment"))
#expect(markdown.contains("| test-model |"))
}
@Test func failureIsReportedAsAFailure() async throws {
let directory = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
try writeText("Hello.", to: directory.appendingPathComponent("source.txt"))
try writeText("Hallo.", to: directory.appendingPathComponent("reference.txt"))
let manifestURL = directory.appendingPathComponent("corpus.json")
try writeText(manifestJSON([segmentJSON(id: "seg-1")]), to: manifestURL)
let manifest = try EvaluationManifestLoader.load(manifestURL: manifestURL)
let runner = EvaluationRunner(
manifest: manifest,
configuration: EvaluationConfiguration(
models: ["test-model"],
runs: 1,
outputDirectory: directory.appendingPathComponent("results")
),
environment: EvaluationEnvironment(
serverVersion: "v",
ollamaVersion: "v",
hardware: "h",
macOS: "m",
models: [:]
),
pipelineFactory: { _ in FailingStreaming() },
warmUp: { _ in },
unload: { _ in }
)
let report = try await runner.run()
#expect(report.models[0].categories[0].failureRate == 100)
#expect(report.models[0].segments[0].failed)
}
}
private func manifestJSON(_ segments: [[String: String]]) -> String {
let object: [String: Any] = ["version": 1, "segments": segments]
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let text = String(data: data, encoding: .utf8)
else {
return "{}"
}
return text
}
private func segmentJSON(
id: String,
source: String = "source.txt",
reference: String = "reference.txt",
referenceKind: String = "human"
) -> [String: String] {
[
"id": id,
"source": source,
"sourceLanguage": "en",
"targetLanguage": "de",
"category": "en-de-prose",
"reference": reference,
"referenceKind": referenceKind,
]
}
private func makeTemporaryDirectory() throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("sprachmittler-eval-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
private func writeText(_ text: String, to url: URL) throws {
try text.write(to: url, atomically: true, encoding: .utf8)
}
private struct ImmediateStreaming: TranslationStreaming {
let translation: String
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
PipelineResult(
translation: translation,
warnings: [],
sourceLanguage: request.captured.source.rawValue,
timing: TranslationTiming(firstTokenMs: 10, totalMs: 20, promptTokens: 3, outputTokens: 4),
chunkCount: 1
)
}
}
private struct FailingStreaming: TranslationStreaming {
func translate(
_ request: TranslationSessionRequest,
onDelta: (@Sendable (String) async -> Void)?
) async throws -> PipelineResult {
throw SprachmittlerError.modelNotInstalled(model: request.model)
}
}