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
5 changes: 3 additions & 2 deletions docs/KNOWN-ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,9 @@ x86 processor, and a table-driven one costs about half a second on the 572 MB cs
come from a writer that gets sizes wrong.

### A pattern constraint is bounded per value, not per run
The match timeout is 100 ms. A pattern using a lookaround falls back to the backtracking engine, and
a million rows at 100 ms each is a run measured in hours. Compilation is not bounded at all: a
A pattern runs on .NET's non-backtracking engine, whose time is linear in the value and which has no
clock. One using a lookaround or a backreference falls back to the backtracking engine, bounded at
100 ms a value, and a million rows at 100 ms each is a run measured in hours. Compilation is not bounded at all: a
pattern with large counted quantifiers costs time and memory before any value is seen.

**Matters when** patterns become admin-authored or config-driven rather than domain-authored.
Expand Down
16 changes: 11 additions & 5 deletions src/TriasDev.Tabular/Mapping/FieldConstraint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,10 @@ public AllowedValues(IEnumerable<string> values, bool ignoreCase = false)
/// in name only. Anchors written into the pattern still work.
/// </para>
/// <para>
/// Bounded in time, and compiled without backtracking. A pattern arrives as data from a calling
/// domain and is applied to every row of a file a user chose; a pattern that can be made to run
/// away would turn one upload into an outage.
/// Compiled without backtracking, whose time is linear in the value, so it needs no clock. A
/// pattern arrives as data from a calling domain and is applied to every row of a file a user
/// chose; a pattern that can be made to run away would turn one upload into an outage. One that
/// needs backtracking — a lookaround, a backreference — is bounded in time instead.
/// </para>
/// </remarks>
public sealed class Pattern : FieldConstraint
Expand All @@ -197,6 +198,9 @@ public Pattern(string expression)
/// <summary>The pattern as it was given.</summary>
public string Expression { get; }

/// <summary>How long one match may run: without limit on the linear engine, the budget on the fallback.</summary>
internal TimeSpan MatchTimeout => _expression.MatchTimeout;

/// <inheritdoc />
public override string Code => ErrorCodes.Value.Pattern;

Expand Down Expand Up @@ -224,8 +228,10 @@ private static Regex Build(string expression)
try
{
// The non-backtracking engine cannot run away by construction, which is worth more
// than the constructs it refuses to compile.
return new Regex(expression, RegexOptions.NonBacktracking | RegexOptions.CultureInvariant, Budget);
// than the constructs it refuses to compile. It gets no clock: a clock there only
// misjudges. The first match in a process builds the engine, under load that
// outran the budget, and .NET then answered false — a valid value failed.
return new Regex(expression, RegexOptions.NonBacktracking | RegexOptions.CultureInvariant, Regex.InfiniteMatchTimeout);
}
catch (NotSupportedException)
{
Expand Down
12 changes: 12 additions & 0 deletions tests/TriasDev.Tabular.Tests/Mapping/FieldConstraintTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Text.RegularExpressions;

using Xunit;

Expand Down Expand Up @@ -81,6 +82,17 @@ public void APatternMustMatchTheWholeValue(string value, bool satisfied)
Assert.Equal("[A-Z]{2}", constraint.Expression);
}

[Fact]
public void JudgesAPatternTheLinearEngineRunsWithoutAClock()
{
// The linear engine cannot run away, so a clock can only do harm there: the first match in a
// process builds the engine, and under load that took longer than the budget. .NET then
// answered false without a word — a valid value failed, found by running the suite thirty
// times. Only the backtracking fallback, which can run away, keeps the budget.
Assert.Equal(Regex.InfiniteMatchTimeout, new FieldConstraint.Pattern("[A-Z]{2}").MatchTimeout);
Assert.NotEqual(Regex.InfiniteMatchTimeout, new FieldConstraint.Pattern("(?=(a+)+b).*").MatchTimeout);
}

[Fact]
public void AnAnchoredPatternMeansWhatItSaid()
{
Expand Down
97 changes: 97 additions & 0 deletions tests/TriasDev.Tabular.Tests/NullArgumentTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System.Text;

using TriasDev.Tabular.Archive;
using TriasDev.Tabular.Csv;
using TriasDev.Tabular.Ods;
using TriasDev.Tabular.Xlsx;

using Xunit;

namespace TriasDev.Tabular.Tests;

/// <summary>
/// Every public entry point refuses a null where it takes none, naming the argument, rather than
/// failing later with a NullReferenceException somewhere inside.
/// </summary>
/// <remarks>
/// Found by mutation testing: removing any one of these checks left the whole suite green, so the
/// contract they state was held by nothing.
/// </remarks>
public sealed class NullArgumentTests
{
private static CancellationToken Token => TestContext.Current.CancellationToken;

private static readonly TextImportField Name = ImportField.Text("name");

private static readonly ImportSchema Schema = new() { Fields = [Name] };

private static readonly MappingPlan Plan = new() { Bindings = [new ColumnBinding { ColumnIndex = 0, FieldName = "name", Header = "name" }] };

private static MemoryStream Csv() => new(Encoding.UTF8.GetBytes("name\nx\n"));

private static CsvCursor Cursor() => new(Csv(), "t.csv");

private static FileProfile Profile()
{
using CsvCursor cursor = Cursor();
return TabularAnalyzer.Analyze(cursor, cancellationToken: Token);
}

public static TheoryData<string, string, Action> Calls => new()
{
{ "TabularFile.Open", "stream", () => TabularFile.Open(null!, "t.csv", cancellationToken: CancellationToken.None) },
{ "TabularFile.Open", "name", () => TabularFile.Open(Csv(), null!, cancellationToken: CancellationToken.None) },
{ "TabularFile.Detect", "stream", () => TabularFile.Detect(null!) },
{ "CsvCursor", "stream", () => _ = new CsvCursor(null!, "t.csv") },
{ "CsvCursor", "sheetName", () => _ = new CsvCursor(Csv(), null!) },
{ "CsvDialectDetector.Detect", "stream", () => CsvDialectDetector.Detect((Stream)null!) },
{ "XlsxCursor", "stream", () => _ = new XlsxCursor(null!) },
{ "OdsCursor", "stream", () => _ = new OdsCursor(null!) },
{ "ArchiveCursor", "stream", () => _ = new ArchiveCursor(null!) },
{ "TabularAnalyzer.Analyze", "cursor", () => TabularAnalyzer.Analyze(null!, cancellationToken: CancellationToken.None) },
{ "TabularExtractor.Extract", "cursor", () => TabularExtractor.Extract(null!, Plan, Schema, cancellationToken: CancellationToken.None) },
{ "TabularExtractor.Extract", "plan", () => TabularExtractor.Extract(Cursor(), null!, Schema, cancellationToken: CancellationToken.None) },
{ "TabularExtractor.Extract", "schema", () => TabularExtractor.Extract(Cursor(), Plan, null!, cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(cursor)", "cursor", () => TabularImporter.Import<string?>(null!, Plan, Schema, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(cursor)", "plan", () => TabularImporter.Import<string?>(Cursor(), null!, Schema, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(cursor)", "schema", () => TabularImporter.Import<string?>(Cursor(), Plan, null!, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(cursor)", "mapper", () => TabularImporter.Import<string?>(Cursor(), Plan, Schema, null!, cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(stream)", "stream", () => TabularImporter.Import<string?>((Stream)null!, "t.csv", Plan, Schema, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(stream)", "name", () => TabularImporter.Import<string?>(Csv(), null!, Plan, Schema, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(stream)", "plan", () => TabularImporter.Import<string?>(Csv(), "t.csv", null!, Schema, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(stream)", "schema", () => TabularImporter.Import<string?>(Csv(), "t.csv", Plan, null!, row => row[Name], cancellationToken: CancellationToken.None) },
{ "TabularImporter.Import(stream)", "mapper", () => TabularImporter.Import<string?>(Csv(), "t.csv", Plan, Schema, null!, cancellationToken: CancellationToken.None) },
{ "MappingPrecheck.Check", "plan", () => MappingPrecheck.Check(null!, Schema, Profile()) },
{ "MappingPrecheck.Check", "schema", () => MappingPrecheck.Check(Plan, null!, Profile()) },
{ "MappingPrecheck.Check", "profile", () => MappingPrecheck.Check(Plan, Schema, null!) },
{ "MappingPlanValidator.Validate", "plan", () => MappingPlanValidator.Validate(null!, Schema) },
{ "MappingPlanValidator.Validate", "schema", () => MappingPlanValidator.Validate(Plan, null!) },
{ "MappingPlan.ByHeader", "sheet", () => MappingPlan.ByHeader(null!, Schema) },
{ "MappingPlan.ByHeader", "schema", () => MappingPlan.ByHeader(Profile().Sheets[0], null!) },
{ "MappingPlan.ByHeader", "matches", () => MappingPlan.ByHeader(Profile().Sheets[0], Schema, (Func<string, ImportField, bool>)null!) },
{ "HeaderVariant.TryParse", "variants", () => HeaderVariant.TryParse("name (en)", null!, out _, out _) },
{ "ImportField.Text", "name", () => ImportField.Text(null!) },
{ "ImportField.Translated", "name", () => ImportField.Translated(null!, ["en"]) },
{ "ImportField.Translated", "variants", () => ImportField.Translated("title", null!) },
{ "TextImportField.Must", "rule", () => Name.Must("rule", null!) },
{ "IntegerImportField.Must", "rule", () => ImportField.Integer("n").Must("rule", null!) },
{ "DecimalImportField.Must", "rule", () => ImportField.Decimal("n").Must("rule", null!) },
{ "DateImportField.Must", "rule", () => ImportField.Date("n").Must("rule", null!) },
{ "FieldConstraint.AllowedValues", "values", () => _ = new FieldConstraint.AllowedValues(null!) },
{ "FieldConstraint.Pattern", "expression", () => _ = new FieldConstraint.Pattern(null!) },
{ "FieldConstraint.Rule", "code", () => _ = new FieldConstraint.Rule(null!, _ => true) },
{ "FieldConstraint.Rule", "predicate", () => _ = new FieldConstraint.Rule("rule", null!) },
{ "CheckDigits.Luhn", "value", () => CheckDigits.Luhn(null!) },
{ "CheckDigits.Mod97", "value", () => CheckDigits.Mod97(null!) },
{ "ErrorCodes.IsReserved", "code", () => ErrorCodes.IsReserved(null!) },
};

[Theory]
[MemberData(nameof(Calls))]
public void RefusesANullItTakesNone(string call, string parameter, Action invoke)
{
ArgumentException error = Assert.ThrowsAny<ArgumentException>(invoke);

Assert.True(parameter == error.ParamName, $"{call}: refused {error.ParamName ?? "(unnamed)"} for {parameter}");
}
}
Loading