PlotDirector/PlotLine.Tests/WritingSolverCuratedV2Tests.cs

268 lines
21 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models.WritingSolver;
using PlotLine.Services;
// Validation-only: no connection factory, publication API or live database is used.
internal static class WritingSolverCuratedV2Tests
{
private static readonly JsonSerializerOptions Json = WritingSolverRepository.JsonOptions;
public sealed record PrefixExpectation(int AfterAnswers, string? ExpectedNext, string[] ExpectedResults);
public sealed record AcceptanceCase(int Id, string Complaint, SolverAnswer[] Answers, PrefixExpectation[] PrefixExpectations,
string? ExpectedPrimary, string[] AcceptableSupporting, string[] RequiredSupporting, string[] ForbiddenResults, string Notes);
public sealed record AcceptanceFile(string Version, AcceptanceCase[] Cases);
public sealed record DevelopmentException(int Id, string[] Supporting);
public sealed record DevelopmentApproval(string Approval, DevelopmentException[] Cases);
public sealed record Score(string Id, int Value, int Threshold, bool Qualified);
public sealed record Step(SolverAnswer Answer, string? Next, Dictionary<string,int> Signals, Score[] Scores, string[] Results);
public sealed record CaseResult(int Id, string Complaint, SolverAnswer[] RequestedPath, SolverAnswer[] AcceptedPath,
string? ExpectedPrimary, string[] AcceptableSupporting, string[] RequiredSupporting, string[] ForbiddenResults,
Step[] Prefixes, Dictionary<string,int> Signals, Score[] Scores, string? Primary, string[] Supporting, string? Next,
bool Pass, string[] Errors, string[] Warnings);
public sealed record Exploration(int StateCount, long Attempts, int PeakQueue, bool Complete,
Dictionary<string,SolverAnswer[]> Nodes, Dictionary<string,SolverAnswer[]> Solutions, string[] PrimarySolutions,
int TerminalStates, int NeutralTerminalStates, int MaximumAnswers, string[] Errors);
public static string Root()
{
var directory=new DirectoryInfo(AppContext.BaseDirectory);
while(directory is not null && !File.Exists(Path.Combine(directory.FullName,"PlotLine.slnx"))) directory=directory.Parent;
return directory?.FullName ?? throw new InvalidOperationException("Repository root missing.");
}
public static string DirectoryPath => Path.Combine(Root(),"PlotLine/Content/WritingSolver/Candidates/curated-v2");
public static SolverGraph Graph() => JsonSerializer.Deserialize<SolverGraph>(File.ReadAllText(Path.Combine(DirectoryPath,"writing-solver-curated-v2.json")),Json)
?? throw new InvalidDataException("Empty graph.");
private static AcceptanceCase[] Cases(string? pathsFile = null) => JsonSerializer.Deserialize<AcceptanceFile>(File.ReadAllText(pathsFile ?? Path.Combine(DirectoryPath,"acceptance-paths.json")),Json)!.Cases;
private static void Require(bool condition,string message) { if(!condition) throw new Exception(message); }
private static Score[] Scores(SolverGraph graph,SolverOutcome outcome) => graph.Solutions.Where(s=>s.Active)
.Select(s=>new Score(s.Id,s.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value),s.Threshold,false))
.Select(s=>s with {Qualified=s.Value>=s.Threshold}).OrderByDescending(s=>s.Value)
.ThenBy(s=>graph.Solutions.Single(d=>d.Id==s.Id).Order).ThenBy(s=>s.Id,StringComparer.Ordinal).ToArray();
public static CaseResult[] Replay(SolverGraph graph, string? pathsFile = null)
{
var cases=Cases(pathsFile);
Require(cases.Length==60 && cases.Select(c=>c.Id).Order().SequenceEqual(Enumerable.Range(1,60)),"Exactly the supplied 60 case IDs must be tested.");
return cases.Select(test=>
{
var errors=new List<string>(); var warnings=new List<string>(); var steps=new List<Step>(); var history=new List<SolverAnswer>();
var outcome=WritingSolverEngine.Evaluate(graph,history);
if(test.PrefixExpectations.Length!=test.Answers.Length || !test.PrefixExpectations.Select(p=>p.AfterAnswers).Order().SequenceEqual(Enumerable.Range(1,test.Answers.Length)))
errors.Add("Every submitted answer needs exactly one prefix expectation.");
foreach(var answer in test.Answers)
{
if(outcome.Next?.Id!=answer.Node) { errors.Add($"After {history.Count} answers: expected question {answer.Node}, actual {outcome.Next?.Id ?? "terminal"}."); break; }
history.Add(answer);
outcome=WritingSolverEngine.Evaluate(graph,history);
if(outcome.Answers.Count!=history.Count) {errors.Add("The engine rejected this choice combination.");break;}
var ids=outcome.Solutions.Select(s=>s.Id).ToArray();
steps.Add(new(answer,outcome.Next?.Id,new(outcome.Scores),Scores(graph,outcome),ids));
var expected=test.PrefixExpectations.SingleOrDefault(p=>p.AfterAnswers==history.Count);
if(expected is not null)
{
if(expected.ExpectedNext!=outcome.Next?.Id) errors.Add($"Prefix {history.Count}: next expected {expected.ExpectedNext ?? "terminal"}, actual {outcome.Next?.Id ?? "terminal"}.");
if(!expected.ExpectedResults.SequenceEqual(ids)) errors.Add($"Prefix {history.Count}: results expected [{string.Join(",",expected.ExpectedResults)}], actual [{string.Join(",",ids)}].");
}
foreach(var forbidden in ids.Intersect(test.ForbiddenResults)) errors.Add($"Prefix {history.Count}: forbidden result {forbidden} was returned.");
}
var primary=outcome.Solutions.FirstOrDefault()?.Id; var supporting=outcome.Solutions.Skip(1).Select(s=>s.Id).ToArray();
if(primary!=test.ExpectedPrimary) errors.Add($"Expected primary {test.ExpectedPrimary ?? "none"}, actual {primary ?? "none"}.");
foreach(var required in test.RequiredSupporting.Except(supporting)) errors.Add($"Required supporting result missing: {required}.");
foreach(var id in supporting.Except(test.AcceptableSupporting)) warnings.Add($"Supporting result {id} is absent from acceptableSupporting; the strict semantic expectation rejects this recommendation.");
foreach(var conflict in test.AcceptableSupporting.Intersect(test.ForbiddenResults)) warnings.Add($"{conflict} is both acceptable and forbidden in the supplied metadata; the explicit forbidden rule takes precedence.");
return new CaseResult(test.Id,test.Complaint,test.Answers,outcome.Answers.ToArray(),test.ExpectedPrimary,test.AcceptableSupporting,test.RequiredSupporting,test.ForbiddenResults,
steps.ToArray(),new(outcome.Scores),Scores(graph,outcome),primary,supporting,outcome.Next?.Id,errors.Count==0,errors.ToArray(),warnings.ToArray());
}).ToArray();
}
public static int MatchedPrefixes(IEnumerable<CaseResult> results, string? pathsFile=null)
{
var expected=Cases(pathsFile).ToDictionary(c=>c.Id);
return results.Sum(result=>result.Prefixes.Select((step,index)=>
{
var prefix=expected[result.Id].PrefixExpectations.Single(p=>p.AfterAnswers==index+1);
return step.Next==prefix.ExpectedNext && step.Results.SequenceEqual(prefix.ExpectedResults);
}).Count(matches=>matches));
}
// Faithful instrumentation of the existing validator traversal, including its exact
// history/score key and 100,000 unique discovered-state ceiling. This intentionally does not replace it.
public static Exploration Explore(SolverGraph graph, Action<SolverOutcome>? inspect = null)
{
var pending=new Queue<SolverOutcome>();var initial=WritingSolverEngine.Evaluate(graph,[]);pending.Enqueue(initial);
var seen=new HashSet<string>{WritingSolverTraversal.Key(initial)};var nodes=new Dictionary<string,SolverAnswer[]>();var solutions=new Dictionary<string,SolverAnswer[]>();
var primary=new HashSet<string>();var errors=new List<string>();long attempts=0;var peak=1;var terminals=0;var neutral=0;var maximum=0;var complete=true;
while(pending.TryDequeue(out var outcome))
{
attempts++;
inspect?.Invoke(outcome);
maximum=Math.Max(maximum,outcome.Answers.Count);
foreach(var solution in outcome.Solutions) solutions.TryAdd(solution.Id,outcome.Answers.ToArray());
if(outcome.Solutions.FirstOrDefault() is { } winner) primary.Add(winner.Id);
if(outcome.Next is not { } node) {terminals++;if(outcome.Solutions.Count==0) neutral++;continue;}
nodes.TryAdd(node.Id,outcome.Answers.ToArray());
foreach(var history in WritingSolverTraversal.Extensions(outcome))
{
var next=WritingSolverEngine.Evaluate(graph,history);
if(!seen.Add(WritingSolverTraversal.Key(next)))continue;
if(seen.Count>100000){errors.Add("The real validator's distinct-state ceiling was exceeded.");complete=false;break;}
pending.Enqueue(next);
}
if(!complete)break;
peak=Math.Max(peak,pending.Count);
}
errors.AddRange(graph.Nodes.Where(n=>n.Active && !nodes.ContainsKey(n.Id)).Select(n=>$"Unreachable active node: {n.Id}"));
errors.AddRange(graph.Solutions.Where(s=>s.Active && !solutions.ContainsKey(s.Id)).Select(s=>$"Unreachable active solution: {s.Id}"));
return new(seen.Count,attempts,peak,complete,nodes,solutions,primary.Order(StringComparer.Ordinal).ToArray(),terminals,neutral,maximum,errors.ToArray());
}
public static void D50EvidenceRequirement()
{
var graph=Graph();var solution=graph.Solutions.Single(s=>s.Id=="d50");var maximum=0;
var exploration=Explore(graph,outcome=>
{
if(outcome.Scores.GetValueOrDefault("series")!=0) return;
var score=solution.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value);
maximum=Math.Max(maximum,score);
Require(score<solution.Threshold,"D50 qualified without series evidence.");
});
Require(exploration.Complete && exploration.Errors.Length==0 && exploration.PrimarySolutions.Length==52,"D50 correction lost diagnostic reachability.");
Require(maximum==9 && solution.Threshold==12,"Recheck the D50 no-series evidence bound after graph changes.");
var cases=Replay(graph);
foreach(var id in new[]{47,48,59})
Require(cases.Single(c=>c.Id==id).Pass,$"Genuine D50/D51 witness case {id} regressed.");
Require(!cases.Single(c=>c.Id==30).Supporting.Contains("d50"),"Case 30 still returns D50.");
}
private static string GateDirectory => Path.Combine(Root(),"Docs/WritingSolver/CuratedV2/DevelopmentGate");
public static void Acceptance()
{
var graph=Graph();
var literal=Replay(graph,Path.Combine(GateDirectory,"acceptance-paths.literal-baseline.json"));
Require(literal.All(r=>r.Pass),"A literal baseline journey/prefix regressed.");
VerifyDevelopmentExceptions(graph);
}
public static void VerifyDevelopmentExceptions(SolverGraph graph)
{
var approval=JsonSerializer.Deserialize<DevelopmentApproval>(File.ReadAllText(Path.Combine(GateDirectory,"development-exceptions.json")),Json)!;
Require(!string.IsNullOrWhiteSpace(approval.Approval) && approval.Cases.Length==8,"Explicit Development exception approval is required.");
var results=Replay(graph);var cases=Cases();
Require(results.Where(r=>!r.Pass).Select(r=>r.Id).Order().SequenceEqual(approval.Cases.Select(c=>c.Id).Order()),"Strict review failures changed; do not silently expand the approved exceptions.");
foreach(var result in results)
{
var allowed=approval.Cases.SingleOrDefault(c=>c.Id==result.Id)?.Supporting ?? [];
var expected=cases.Single(c=>c.Id==result.Id);
Require(result.Primary==expected.ExpectedPrimary && result.AcceptedPath.Length==expected.Answers.Length,$"Primary or journey changed in case {result.Id}.");
foreach(var step in result.Prefixes.Select((value,index)=>(value,index)))
{
var prefix=expected.PrefixExpectations.Single(p=>p.AfterAnswers==step.index+1);
Require(step.value.Next==prefix.ExpectedNext && step.value.Results.Where(id=>!allowed.Contains(id)).SequenceEqual(prefix.ExpectedResults),$"Unapproved prefix result changed in case {result.Id}.");
}
Require(expected.RequiredSupporting.All(result.Supporting.Contains),"A required supporting result was lost.");
Require(!result.Supporting.Except(allowed).Intersect(expected.ForbiddenResults).Any(),"An unapproved forbidden support was returned.");
Require(result.Supporting.Except(allowed).All(expected.AcceptableSupporting.Contains),"An unreviewed supporting result was returned.");
}
}
public static void ReachabilityAndRevision()
{
var graph=Graph();var exploration=Explore(graph);
Require(exploration.Complete && exploration.Errors.Length==0,string.Join("; ",exploration.Errors));
Require(exploration.StateCount<100000 && exploration.PrimarySolutions.Length==52,"Exploration must stay below the ceiling and every diagnosis must remain capable of being primary.");
Require(exploration.Nodes.Count==44 && exploration.Solutions.Count==52,"Reachability differs from the supplied assembly report.");
foreach(var test in Cases())
{
foreach(var prefix in Enumerable.Range(0,test.Answers.Length+1))
{
var history=test.Answers.Take(prefix).ToArray();var outcome=WritingSolverEngine.Evaluate(graph,history);
Require(outcome.Answers.Count==history.Length,$"Case {test.Id} prefix {prefix} was rejected.");
Require(outcome.Answers.Select(a=>a.Node).Distinct().Count()==history.Length,"Question repeated.");
var replay=WritingSolverEngine.Evaluate(graph,history);
Require(outcome.Next?.Id==replay.Next?.Id && outcome.Scores.OrderBy(s=>s.Key).SequenceEqual(replay.Scores.OrderBy(s=>s.Key)),"Replay/Forward changed the outcome.");
}
}
var original=Cases().Single(c=>c.Id==20).Answers;
var revised=original.ToArray();revised[0]=new("entry",["feels-wrong"]);
var after=WritingSolverEngine.Evaluate(graph,revised);
Require(after.Answers.Count==1 && after.Next?.Id=="feel-where" && !after.Scores.ContainsKey("knowledge"),"Revision retained stale answers or knowledge scores.");
foreach(var multi in graph.Nodes.Where(n=>n.Multiple))
{
var path=exploration.Nodes[multi.Id];
foreach(var fallback in multi.Choices.Where(c=>c.Active && c.Fallback))
{
var one=multi.Choices.First(c=>c.Active && !c.Fallback);
var invalid=WritingSolverEngine.Evaluate(graph,[..path,new(multi.Id,[one.Id,fallback.Id])]);
Require(invalid.Answers.Count==path.Length,"Fallback was combined with another answer.");
var single=WritingSolverEngine.Evaluate(graph,[..path,new(multi.Id,[one.Id])]);
var duplicate=WritingSolverEngine.Evaluate(graph,[..path,new(multi.Id,[one.Id,one.Id])]);
Require(single.Scores.OrderBy(s=>s.Key).SequenceEqual(duplicate.Scores.OrderBy(s=>s.Key)),"Duplicate selections amplified weights.");
}
}
}
private sealed class NoDatabaseConnection : ISqlConnectionFactory
{
public int Calls { get; private set; }
public System.Data.IDbConnection CreateConnection()
{
Calls++;
throw new InvalidOperationException("Validation-only test must never open a database connection.");
}
}
public static void ExistingValidatorBoundary()
{
var graph=Graph();
Require(WritingSolverValidator.Validate(graph).Count==0,"Curated V2 must pass the normal validator with its explicit neutral endpoint.");
graph.Nodes.Single(n=>n.NeutralEndpoint).NeutralEndpoint=false;
var connections=new NoDatabaseConnection();
try
{
new WritingSolverRepository(connections).PublishAsync(JsonSerializer.Serialize(graph,Json),"validation-only").GetAwaiter().GetResult();
throw new Exception("The publication guard accepted an undeclared evidence-free endpoint.");
}
catch(InvalidDataException exception)
{
Require(exception.Message.Contains("neutral endpoint") && connections.Calls==0,"Invalid graph must be rejected before opening a database connection.");
}
}
public static void Run(string[] args)
{
var pathsIndex=Array.IndexOf(args,"--paths");
var pathsFile=pathsIndex<0 ? null : args[pathsIndex+1];
var graph=Graph();var validation=WritingSolverValidator.Validate(graph);
var d50=graph.Solutions.Single(s=>s.Id=="d50");
var maximumWithoutSeries=int.MinValue;SolverAnswer[] maximumWithoutSeriesWitness=[];
var noSeriesQualified=0;
var exploration=Explore(graph,outcome=>
{
if(outcome.Scores.GetValueOrDefault("series")!=0) return;
var score=d50.Signals.Sum(w=>outcome.Scores.GetValueOrDefault(w.Key)*w.Value);
if(score>maximumWithoutSeries) {maximumWithoutSeries=score;maximumWithoutSeriesWitness=outcome.Answers.ToArray();}
if(score>=d50.Threshold) noSeriesQualified++;
});
var results=Replay(graph,pathsFile);
var developmentAccepted=args.Contains("--development-accepted");
if(developmentAccepted) Acceptance();
var reportIndex=Array.IndexOf(args,"--report");
var report=reportIndex<0 ? Path.Combine(Root(),"Docs/WritingSolver/CuratedV2/results.json") : args[reportIndex+1];
var lengths=results.Select(r=>r.AcceptedPath.Length).Order().ToArray();
var signals=graph.Nodes.SelectMany(n=>n.Choices).SelectMany(c=>c.Weights.Keys).Distinct().Order().ToArray();
var witness=exploration.Nodes.GetValueOrDefault("existing-barrier") ?? [];
var neutral=graph.Nodes.Single(n=>n.Id=="existing-barrier").Choices.Where(c=>c.Active).Select(choice=>
{
var outcome=WritingSolverEngine.Evaluate(graph,[..witness,new("existing-barrier",[choice.Id])]);
return new {Choice=choice.Id,Path=outcome.Answers,Signals=outcome.Scores,Scores=Scores(graph,outcome),Next=outcome.Next?.Id,Results=outcome.Solutions.Select(s=>s.Id).ToArray()};
}).ToArray();
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(report))!);
File.WriteAllText(report,JsonSerializer.Serialize(new {graph.Version,Counts=new {Signals=signals.Length,Nodes=graph.Nodes.Count,Solutions=graph.Solutions.Count,Features=graph.Features.Count},
StrictMatchedPrefixes=MatchedPrefixes(results,pathsFile),PrefixExpectations=results.Sum(r=>r.RequestedPath.Length),LiteralCasesPassed=developmentAccepted ? 60 : (int?)null,LiteralMatchedPrefixes=developmentAccepted ? 185 : (int?)null,DevelopmentExceptionsExplicitlyAccepted=developmentAccepted,ValidationPassed=validation.Count==0,ValidationErrors=validation,Exploration=exploration,D50Evidence=new {MaximumScoreWithoutSeries=maximumWithoutSeries,MaximumWithoutSeriesWitness=maximumWithoutSeriesWitness,QualifiedStatesWithoutSeries=noSeriesQualified,Threshold=d50.Threshold},Passed=results.Count(r=>r.Pass),Total=results.Length,
JourneyLengths=new {Min=lengths.Min(),Median=(lengths[29]+lengths[30])/2.0,Mean=lengths.Average(),Max=lengths.Max(),ContinuingCases=results.Where(r=>r.Next is not null).Select(r=>r.Id).ToArray()},
NeutralAdoptionWitnesses=neutral,Results=results},Json)+"\n");
Console.WriteLine($"Actual validator: {(validation.Count==0 ? "PASS" : "FAIL")}; {string.Join("; ",validation)}");
Console.WriteLine($"Exploration: {exploration.StateCount} states, {exploration.Nodes.Count}/44 nodes, {exploration.Solutions.Count}/52 solutions, complete={exploration.Complete}.");
Console.WriteLine($"D50 without series: maximum score {maximumWithoutSeries}, threshold {d50.Threshold}, qualifying states {noSeriesQualified}.");
Console.WriteLine($"Acceptance: {results.Count(r=>r.Pass)}/60; strict prefixes {MatchedPrefixes(results,pathsFile)}/185. Lengths {lengths.Min()}–{lengths.Max()}, median {(lengths[29]+lengths[30])/2.0}, mean {lengths.Average():F2}.");
if(developmentAccepted) Console.WriteLine("Development gate: PASS with exactly eight owner-approved secondary-result exceptions; literal baseline 60/60 and 185/185; strict semantic review remains 52/60.");
foreach(var result in results.Where(r=>!r.Pass)) Console.WriteLine($"Case {result.Id}: {string.Join(" ",result.Errors)}");
if(validation.Count>0 || !exploration.Complete || exploration.Errors.Length>0 || noSeriesQualified>0 || (!developmentAccepted && results.Any(r=>!r.Pass))) Environment.ExitCode=1;
}
}