Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/oracles.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,43 @@ with the class as what varies it.
nothing holds it. Ids are a letter (R ranges, M multirange, S sets, J literals/JSON/TypeConverter, E
EF Core, A hosting/AOT), two digits and a slug, sorted.

## Sibling parity

The claims hold each promise where a document makes it, so they find a bug at the site they check
and miss it at the sibling site that makes the same promise implicitly. The changelog shows that a
bug at one site tends to come back at its siblings. The receiver-shaped dispatch went from
`IsAdjacentTo` to `IsStrictlyLeftOf` to `RangeSet.Except(TRange)`, and the wrapper arities kept
lagging their primitive set. A **sibling parity sweep** (`*ParityTests` in the conventions project,
kind `differential`) runs two things that must agree on the same input and compares their answers.
It needs no ground truth: when the siblings disagree, one of them is wrong.

| Sweep | One side | The other side |
|---|---|---|
| `SetWrapperParityTests` | each primitive value set | its wrapper arity closed over an identity element (`Same<T>`, `SameText`) |
| `RangeSetLiftParityTests` | each range operation, predicate and accessor | the same on the one-element `RangeSet` holding the range |
| `LiteralEntryPointParityTests` | `Parse(string)` of a literal | the span overload, `TryParse`, JSON, the `TypeConverter` and configuration binding |

The rules are the ones for any oracle, plus three of their own:

- **The pair must be a promise.** Compare two sites only where a document says, or the design
requires, that they agree. Where the documents set them apart, compare through the documented
mapping, or leave the input out and cite the document in a comment. For example, a NodaTime
wrapper set refuses a non-ISO element that its primitive normalizes, and a `TypeConverter` reads
`""` as an absent value.
- **The identity has to be real.** `SetWrapperParityTests` closes each family over an element that
adds nothing: it parses with the exact inverse of the primitive's text form (`DateTime` with
`RoundtripKind`, NodaTime with its ISO pattern) and compares as the primitive does. A wrapper that
added anything would turn a family defect into a harness defect.
- **Make sure both sides really are distinct calls.** In generic code `TSet.Parse(string, …)` binds
to the span overload (see [testing.md](testing.md#the-sibling-parity-sweeps)), so a string-versus-span
comparison has to go through `StringOverloads`. A seed that breaks one side shows whether the sweep
reaches it.

A disagreement goes through `Candidates.Verdict` like any other, with each failure line starting
with the row's type name. A disagreement already filed against another oracle gets its own rows here
under the same issue. #109 is the example: PostgreSQL disagrees with `IsUnboundedStart` on `(,)`, and
so does the range's own one-element multirange.

## Generated operands

Most sweeps enumerate their cases: shapes, small universes, five cultures. `DifferentialFuzzParityTests`
Expand Down
50 changes: 50 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,56 @@ overloads, `Add`, `Remove`, `Contains`, an unquoted `NULL` in the array literal,
refuses rather than drops. It runs over families whose element type is a reference type, which is
`StringSet` alone today and whatever is added later without anyone having to remember.

### The Sibling Parity Sweeps

A bug found at one API site tends to come back at a sibling site that makes the same promise. The
changelog shows it repeatedly: `IsAdjacentTo` (6.2.1), then `IsStrictlyLeftOf` and `Except` (7.0.0),
then `RangeSet.Except(TRange)` (8.0.0). The wrapper arities kept lagging their primitive set. And
`==`/`!=` went untested on 18 of 20 set types. A claim-driven oracle checks each site against its own
document, so it can't see a promise two sites share without saying so. These three sweeps
(conventions project, one `[DynamicData]` row per discovered type) compare the two siblings directly.
They assert no ground truth: when the siblings disagree, one of them is wrong, and the failure line
names both answers.

- **`SetWrapperParityTests`**: each primitive set against its wrapper arity closed over an
*identity* element (`Int32Set` against `Int32Set<Same<int>>`, `StringSet` against
`StringSet<SameText>`, in `IdentityWrappers.cs`). An identity element parses, formats and compares
exactly as its primitive does, so the family's own code is the only difference. That's the
opposite of `WrapperElements`, whose elements get something wrong on purpose. The sweep runs the
family's probes plus its extremes, every subset shape, array literals derived from the element
texts (quoted, whitespace-padded, duplicated, out of order, empty, `NULL`, malformed) and JSON
documents (reordered, mistyped, quoted, padded). It compares every operation, `ParseValue` and
`FormatValue`, both overloads of `Parse` and `TryParse`, `ToString` with each format and provider,
the `TypeConverter`, JSON token kinds, and each sibling reading the other's document. It wants the
same element texts in the same order, or the same exception type.
- **`RangeSetLiftParityTests`**: each range against the one-element `RangeSet` holding it, over the
shape matrix `DomainParityOracleTests` uses (`RangeSpecs.cs`), extended with bounds at the domain's
minimum and maximum. For every ordered pair it compares each predicate with the set-set and
set-range overloads, and each operation with the named method and the operator (`|`, `&`, `-`).
For every range it compares each accessor, `Merge`, `Complement`, the literal, and `Contains(T)`
at every grid point. Results are compared as literals, so the bound values and inclusivity have to
match, not just a few `Contains` answers.
- **`LiteralEntryPointParityTests`**: one literal through every entry point: `Parse` and `TryParse`
(string and span), a JSON string, the `TypeConverter` and `IConfiguration` binding. It covers every
range union and each sealed variant (the union's answer narrowed to the variant's shape), every
multirange (including its explicit `IParsable` implementation) and every value set. The entry
points must produce equal values, or all refuse. A value set's JSON is its element array, so it
skips the JSON step here; `SetWrapperParityTests` covers that array. The empty string is an absent
value to the `TypeConverter` and the binder by design, so the converter and the binder never see it.

The sweeps run in a few seconds altogether. Each one is seeded (`test/oracles/seeds/`), and their
disagreements are candidates in `candidates.json`: #141 (wrapper JSON reads accept tokens the
primitive refuses) and #109 (`IsUnboundedStart`/`IsUnboundedEnd` on `(,)`), found again here between
a range and its own multirange.

**The `Parse(string)` trap.** In generic code constrained on `IRangeFactory` or `IValueSetFactory`,
`TSet.Parse(text, provider)` with a `string` argument calls the *span* overload. Both interfaces derive
from `ISpanParsable<TSelf>`. Overload resolution drops the base interface's `IParsable<TSelf>`
candidate whenever the derived interface's span candidate applies, and the implicit string-to-span
conversion makes it apply. So a sweep that means to compare the two overloads compares the span one
with itself. Call the string overloads through `StringOverloads` (constrained on `IParsable<TSelf>`
alone). The parity sweeps do this, and their `TryParse` seed was missed until they did.

### Shape-Combination Matrix

Every binary operation test must cover all five range shapes: `Finite`, `UnboundedStart`, `UnboundedEnd`, `EmptyRange`, `Infinity`. Tests instantiate the "other" operand in each shape and verify the result type and value.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Diagnostics;
using CodoMetis.ValueRanges.Core;
using CodoMetis.ValueRanges.Oracles;
using NodaTime;
using static CodoMetis.ValueRanges.Conventions.Tests.RangeSpecs;

namespace CodoMetis.ValueRanges.Conventions.Tests;

Expand Down Expand Up @@ -39,40 +39,16 @@ public sealed class DomainParityOracleTests
{
private const string OracleName = nameof(DomainParityOracleTests);

private enum Shape { Empty, Infinity, Finite, UnboundedStart, UnboundedEnd }

private sealed record Spec(Shape Shape, int Start, int End, bool StartInclusive, bool EndInclusive);

private sealed record Case<TRange>(string Label, TRange Range, HashSet<int> Model) where TRange : notnull;

private static readonly DateTime s_dateTimeOrigin = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
private static readonly LocalDateTime s_localOrigin = new(2026, 1, 1, 0, 0);
private static readonly Instant s_instantOrigin = Instant.FromUtc(2026, 1, 1, 0, 0);

/// <summary>Grid index to element, order-preserving; a discrete type's step is one grid point.</summary>
private static readonly Dictionary<Type, Delegate> s_embeddings = new()
{
[typeof(int)] = (Func<int, int>)(k => k),
[typeof(long)] = (Func<int, long>)(k => k),
[typeof(decimal)] = (Func<int, decimal>)(k => k * 0.5m),
[typeof(DateOnly)] = (Func<int, DateOnly>)(k => new DateOnly(2026, 1, 1).AddDays(k)),
[typeof(TimeOnly)] = (Func<int, TimeOnly>)(k => new TimeOnly(9, 0).AddMinutes(30 * k)),
[typeof(DateTime)] = (Func<int, DateTime>)(k => s_dateTimeOrigin.AddMinutes(30 * k)),
[typeof(DateTimeOffset)] = (Func<int, DateTimeOffset>)(k => new DateTimeOffset(s_dateTimeOrigin.AddMinutes(30 * k), TimeSpan.FromHours(1))),
[typeof(LocalDate)] = (Func<int, LocalDate>)(k => new LocalDate(2026, 1, 1).PlusDays(k)),
[typeof(LocalDateTime)] = (Func<int, LocalDateTime>)(k => s_localOrigin.PlusMinutes(30 * k)),
[typeof(Instant)] = (Func<int, Instant>)(k => s_instantOrigin.Plus(Duration.FromMinutes(30 * k))),
[typeof(YearMonth)] = (Func<int, YearMonth>)(k => new YearMonth(2026, 1).PlusMonths(k))
};

[TestMethod]
public void Discovery_FindsEveryRangeType_AndEveryElementHasAnEmbedding()
{
var types = RangeProbes.AllRangeTypes().ToList();

Assert.IsTrue(types.Count >= 11, $"Discovered {types.Count} range types, fewer than the 11 known to exist.");

var unembedded = types.Where(pair => !s_embeddings.ContainsKey(pair.Element)).Select(pair => pair.Range.Name).ToList();
var unembedded = types.Where(pair => !Embeddings.ContainsKey(pair.Element)).Select(pair => pair.Range.Name).ToList();
Assert.AreEqual(0, unembedded.Count,
"A range type's element has no embedding, so the sweep cannot reach it — add one: " + string.Join(", ", unembedded));
}
Expand All @@ -85,7 +61,7 @@ public void EveryRangeType_EveryOrderedPair_MatchesSetTheory()

foreach (var (range, element) in RangeProbes.AllRangeTypes())
{
if (!s_embeddings.ContainsKey(element)) continue; // reported by the discovery test
if (!Embeddings.ContainsKey(element)) continue; // reported by the discovery test
var result = Reflect.InvokeGeneric<(int Checks, List<string> Failures)>(typeof(DomainParityOracleTests), nameof(Sweep), range, element);
Assert.IsTrue(result.Checks > 100_000, $"{range.Name}: expected well over 100,000 checks, made {result.Checks}.");
failures.AddRange(result.Failures);
Expand All @@ -100,7 +76,7 @@ private static (int Checks, List<string> Failures) Sweep<TRange, T>()
where TRange : class, IRangeFactory<TRange, T>, IRange<T>
where T : struct, IComparable<T>, IEquatable<T>
{
var valueOf = (Func<int, T>)s_embeddings[typeof(T)];
var valueOf = (Func<int, T>)Embeddings[typeof(T)];
var discrete = TRange.IsDiscrete;

// The discrete grid: one index per value, bounds inside the universe. The continuous grid:
Expand All @@ -109,7 +85,7 @@ private static (int Checks, List<string> Failures) Sweep<TRange, T>()
int[] bounds = discrete ? [1, 2, 3, 4, 5, 6] : [2, 4, 6, 8, 10, 12];

var cases = EnumerateSpecs(bounds)
.Select(spec => new Case<TRange>($"{typeof(TRange).Name} {Describe(spec, k => TRange.FormatValue(valueOf(k), null, System.Globalization.CultureInfo.InvariantCulture))}", Build<TRange, T>(spec, valueOf), ModelOf(spec, gridMax)))
.Select(spec => new Case<TRange>($"{typeof(TRange).Name} {Describe<TRange, T>(spec, valueOf)}", Build<TRange, T>(spec, valueOf), ModelOf(spec, gridMax)))
.ToList();

var failures = new List<string>();
Expand Down Expand Up @@ -178,25 +154,6 @@ void CheckSet(string operation, HashSet<int> actual, HashSet<int> expected)
HashSet<int> ModelOfSet(RangeSet<TRange, T> set) => [.. Enumerable.Range(0, gridMax + 1).Where(k => set.Contains(valueOf(k)))];
}

private static IEnumerable<Spec> EnumerateSpecs(int[] bounds)
{
yield return new(Shape.Empty, 0, 0, false, false);
yield return new(Shape.Infinity, 0, 0, false, false);

foreach (var bound in bounds)
foreach (var inclusive in (bool[]) [true, false])
{
yield return new(Shape.UnboundedStart, 0, bound, false, inclusive);
yield return new(Shape.UnboundedEnd, bound, 0, inclusive, false);
}

foreach (var start in bounds)
foreach (var end in bounds.Where(end => end >= start))
foreach (var startInclusive in (bool[]) [true, false])
foreach (var endInclusive in (bool[]) [true, false])
yield return new(Shape.Finite, start, end, startInclusive, endInclusive);
}

/// <summary>The values a specification holds, from the specification alone.</summary>
private static HashSet<int> ModelOf(Spec spec, int gridMax)
{
Expand All @@ -216,30 +173,6 @@ private static HashSet<int> ModelOf(Spec spec, int gridMax)
static bool AtOrBefore(int k, int bound, bool inclusive) => k < bound || (k == bound && inclusive);
}

private static TRange Build<TRange, T>(Spec spec, Func<int, T> valueOf)
where TRange : IRangeFactory<TRange, T>, IRange<T>
where T : struct, IComparable<T>, IEquatable<T> =>
spec.Shape switch
{
Shape.Empty => TRange.Empty,
Shape.Infinity => TRange.Infinite,
Shape.Finite => TRange.CreateFinite(valueOf(spec.Start), valueOf(spec.End), spec.StartInclusive, spec.EndInclusive),
Shape.UnboundedStart => TRange.CreateUnboundedStart(valueOf(spec.End), spec.EndInclusive),
Shape.UnboundedEnd => TRange.CreateUnboundedEnd(valueOf(spec.Start), spec.StartInclusive),
_ => throw new UnreachableException()
};

private static string Describe(Spec spec, Func<int, string> text) =>
spec.Shape switch
{
Shape.Empty => "empty",
Shape.Infinity => "(,)",
Shape.Finite => $"{(spec.StartInclusive ? '[' : '(')}{text(spec.Start)},{text(spec.End)}{(spec.EndInclusive ? ']' : ')')}",
Shape.UnboundedStart => $"(,{text(spec.End)}{(spec.EndInclusive ? ']' : ')')}",
Shape.UnboundedEnd => $"{(spec.StartInclusive ? '[' : '(')}{text(spec.Start)},)",
_ => throw new UnreachableException()
};

private static bool IsContiguous(HashSet<int> values) => values.Count == 0 || values.Max() - values.Min() + 1 == values.Count;

private static HashSet<int> Hull(HashSet<int> values) => values.Count == 0 ? [] : [.. Enumerable.Range(values.Min(), values.Max() - values.Min() + 1)];
Expand Down
Loading