diff --git a/README.md b/README.md index f78661f1..226d631e 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,15 @@ rvtio sheets project.rvt sheets.json The catalog has the sheet number, name, issue date, by-lines and scale, the viewports of each sheet and the elements each sheet owns, plus the text and whole-number project/shared parameters of each sheet (`--params`, `--csv`, `--where NAME=VALUE` with `!=`/`~` and `*`/`?` wildcards). Page size, view placement, the displayed view and 2D content are not decoded; every limit is reported in the catalog itself. See [sheets and viewports](docs/sheets.md). +Compare a model's shared parameter definitions against a Revit shared parameter file by GUID. + +```sh +rvtio audit-shared-parameters project.rvt shared-parameters.txt --report shared-parameter-audit.json +``` + +The command reads both inputs and lists missing definitions, metadata differences, incompatible types and collisions. +See the [audit report format](docs/shared-parameter-audit.md). + Inspect file metadata or inventory a folder recursively without reading geometry or `Partitions`: ```sh diff --git a/docs/shared-parameter-audit.md b/docs/shared-parameter-audit.md new file mode 100644 index 00000000..70f7d035 --- /dev/null +++ b/docs/shared-parameter-audit.md @@ -0,0 +1,34 @@ +# Shared parameter audit + +Run the audit against a Revit project, template, or standalone family and a Revit shared parameter file (FOP): + +```sh +rvtio audit-shared-parameters project.rvt shared-parameters.txt --report shared-parameter-audit.json +``` + +Omit `--report` to print the JSON to standard output. The command opens both inputs for reading. It reads the +parameter definitions of the selected document, including definitions with no assigned values. Audit a standalone +family file separately to check its own definitions. The shared parameter file follows the +[Autodesk definition file format](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-API/files/Revit_API_Developers_Guide/Basic_Interaction_with_Revit_Elements/Parameters/Shared_Parameters/Revit_API_Revit_API_Developers_Guide_Basic_Interaction_with_Revit_Elements_Parameters_Shared_Parameters_Definition_File_html.html). +The command accepts UTF-8 and UTF-16 with a byte-order mark for UTF-16. + +The `rvtio-shared-parameter-audit/1` report lists both sides for each GUID in `parameters`, with model element IDs +and FOP line numbers. A one-to-one match compares the exact name, description when the FOP supplies it, and data type. +For `FAMILYTYPE`, it also compares the target category ID. Empty descriptions in the FOP are compared as empty text. +An empty `findings` array means all comparable fields of the pair agree. + +| Finding | Meaning | +| --- | --- | +| `model-only`, `fop-only` | The GUID appears on one side. A FOP can legitimately contain definitions the document does not use. | +| `name-mismatch`, `description-mismatch` | The GUID matches and the names or descriptions differ. | +| `incompatible-type` | The verified data types differ, or the verified family type category differs. | +| `type-unverified`, `description-unverified` | The comparison needs a type, category, or description the reader could not establish. Unsupported data types keep their raw definition class and spec ID when available. | +| `duplicate-model-guid`, `duplicate-fop-guid` | More than one definition or FOP row on the same side uses this GUID. All candidates are listed. | +| `not-confirmed-in-model` | A FOP GUID was absent from the readable model definitions and the model inventory is partial. | + +The separate `nameCollisions` array lists case-insensitive names used by more than one GUID across either input. +The `unreadableDefinitions` array lists model element IDs whose records were unreadable or ambiguous. + +Exit codes are `0` for a completed audit even when it reports differences, `1` for bad arguments or a report that +cannot be written, `2` for unreadable inputs or invalid FOP syntax, `3` for a reader limit, and `6` for a report +with unreadable or ambiguous definitions. diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index 4c1fc459..057cf7c8 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -20,7 +20,8 @@ A file may lie directly in the folder or in one level of subfolders (`2020`, `20 | `TestData/*.bin` | class blocks captured from project files (38 files, below) | `PageCodecSampleTests` reads every `.rvt` file in the folder and in one level of subfolders, whatever its name, and skips streams over -128 MB. +128 MB. Its short-page test also reads `.rfa`, `.rte`, and `.rft` files. It checks the parity of short tails in gzip streams that pass +their CRC and length checks and in partition streams that pass the framing checks. See [Native short pages](#native-short-pages). `ContainerRewriterSampleTests` copies every `.rvt` file in the folder and in one level of subfolders to a temporary file (deleted after each file; it needs free disk space for the largest file) and compares the compact JSON of the copy with that of the source for the ten largest files of up to 8 MB. @@ -48,6 +49,73 @@ needs no code of its own to skip. Tests that write diagnostic dumps write them t system temporary folder (`TestFiles.Scratch`), one folder per test process, so concurrent runs (both target frameworks of one `dotnet test`, or runs from other checkouts) never share a file; no test uses a fixed absolute path. +## Native short pages + +In the measured short pages, bit `b` (least significant bit first in each byte) belongs to lane `b mod D`, where `D` is an odd +number of lanes. Each lane stores `k - p` data bits followed by `p` parity bits. The page stores the planes for those bits in order, +then zero bits up to the next byte boundary. Its stored length is `ceil(D × k / 8)`. + +The parity is the remainder of the lane's data polynomial multiplied by `y^(p + 2^p - 1 - k)` and divided by the generator +over GF(2). The term `2^p - 1 - k` accounts for the omitted low-order zero coefficients of shortened lanes. In the samples, +shortened lanes occur with `D = 65`. With more lanes, `k = 2^p - 1`. + +| Parity bits per lane (`p`) | Full lane length | Generator | +|---:|---:|---| +| 4 | 15 | `y⁴ + y³ + 1` | +| 5 | 31 | `y⁵ + y³ + 1` | +| 6 | 63 | `y⁶ + y⁵ + 1` | +| 7 | 127 | `y⁷ + y⁶ + 1` | +| 9 | 511 | `y⁹ + y⁵ + 1` | +| 11 | 2,047 | `y¹¹ + y⁹ + 1` | + +The reference test checks stored tails from 82 bytes up to the first long-tail size and requires exactly one parity match. +`PageCodec.Verify` tries every confirmed layout that fits the stored length. A matching layout gives `Valid`. If layouts fit +the length but fail parity or byte padding, the result is `BadTail`. A length with no verified layout gives `UnsupportedTail`. + +For writing, `PageCodec` selects the first row whose capacity holds the content plus the reserved bits. A row's capacity is +`max D × (2^p - 1 - p)` bits. The writer uses 65 lanes when they fit and rounds the required lane count up to an odd number +otherwise. It writes unused bits as zeros. These parameters are inferred from stored lane counts, parity, and the byte offsets +of the gzip or partition terminators in Revit-saved files. At some lengths several reserved-bit counts explain the same layout. + +| Parity bits (`p`) | Max lanes (`D`) | Reserved bits | Last content length for this row (bytes) | +|---:|---:|---:|---:| +| 4 | 77 | 4 | 105 | +| 5 | 79 | 4 | 256 | +| 6 | 77 | 4 | 548 | +| 7 | 85 | 5 | 1,274 | +| 9 | 81 | 7 | 5,081 | +| 11 | 65 | 9 | 16,541 | + +Longer tails use the existing 11-bit layout with at least 67 lanes. `EncodePadded` pads a shorter tail to 44 content bytes +when necessary. For an empty stream or a stream ending exactly on a full page, it appends a 44-byte zero tail. Observed native +gzip pages also exercise the writer's layout selection in the reference test. + +Native saves showed both sides of the 105/106, 256/257, 548/549, 1,274/1,275, and 5,081/5,082 transitions. Revit 2025 +saved a `Global/DocumentIncrementTable` tail with exactly 256 content bytes (an 8-byte prefix and a 248-byte gzip member). +The 307 stored bytes matched the 5-bit code across all 79 lanes, and a native 257-byte tail used the 6-bit code. +Native Revit 2025 partition streams also showed both sides of the 16,541/16,542 transition. The 16,541-byte tail used +65 lanes and occupied 16,632 stored bytes. The 16,542-byte tail used 67 lanes and occupied 17,144 stored bytes. Both used +full-length lanes of 2,047 bits with 11 parity bits per lane. +Revit 2025 opened generated copies on both sides of every writer transition, including 256/257 and 16,541/16,542, +and returned the original model data. + +The native boundary tests read `crcio-tail-.rvt` from `RVTIO_TEST_FILES`. Use the exact decimal content length +without separators, for example `crcio-tail-1274.rvt`. Each case skips if its RVT is absent. + +| Content lengths (bytes) | Expected parity bits per lane | Required single-page stream | +|---|---|---| +| 105 / 106 | 4 / 5 | `Global/PartitionTable` / `Global/DocumentIncrementTable` | +| 256 / 257 | 5 / 6 | `Global/DocumentIncrementTable` | +| 548 / 549 | 6 / 7 | A partition / `Global/DocumentIncrementTable` | +| 1,274 / 1,275 | 7 / 9 | A partition | +| 5,081 / 5,082 | 9 / 11 | A partition | +| 16,541 / 16,542 | 11 / 11 | A partition | + +`NativeShortTailBoundary_UsesTheExpectedParityWidth` measures gzip streams through the end of the member, including +the stream prefix. `NativePartitionTailBoundary_MatchesTheExpectedLayout` measures partition streams through the +terminal marker. Both tests compare the native and re-encoded parity layouts. Changing one parity bit must report +a bad tail while gzip decoding or partition framing still succeeds. + ## Format corpus regression check Set `RVTIO_FORMAT_CORPUS` to a local JSON manifest and run the format corpus test. @@ -123,7 +191,7 @@ Run with the private files: `RVTIO_TEST_FILES= dotnet test` (PowerShell: | `IfcExporterSlabQuantitiesSampleTests` | 3 | 3 | rstbasicsampleproject.rvt, struct25.rvt | | `MultistoryStairCopyTests` | 1 | 1 | rac_advanced_sample_project.rvt | | `OwnElementClassTests` | 1 | 1 | TESTFILE.rvt | -| `PageCodecSampleTests` | 2 | 2 | any `.rvt` project files | +| `PageCodecSampleTests` | 15 | 15 | `.rvt` projects, and `.rfa`, `.rte`, or `.rft` for the short-page census | | `PartitionFramingFuzzTests` | 1 | 1 | TESTFILE.rvt | | `ProjectLengthUnitTests` | 1 | 1 | One Way Sign in Route Analysis.rfa | | `R22TranscoderTests` | 2 | 2 | Test_2025.rvt, TESTFILE.rvt | diff --git a/docs/toc.yml b/docs/toc.yml index 0da795bf..7a2165c5 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -17,6 +17,8 @@ href: glb-export.md - name: Writing and save-as href: writing.md + - name: Shared parameter audit + href: shared-parameter-audit.md - name: Export report and exit codes href: export-report.md - name: Coverage report diff --git a/src/RvtIO.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs index 346702c7..f96c1793 100644 --- a/src/RvtIO.Cli/DowngradeCommand.cs +++ b/src/RvtIO.Cli/DowngradeCommand.cs @@ -157,6 +157,8 @@ private static object Report(DowngradePlanner.Result result, string sourceName, }; } + internal static string SerializeReport(object report) => JsonSerializer.Serialize(report, JsonOptions); + // The report is written beside its target and moved over it, so a failed write leaves no half file and a link keeps its content. internal static int WriteReport(TextWriter error, string? reportPath, object report, int exitCode) { @@ -164,7 +166,7 @@ internal static int WriteReport(TextWriter error, string? reportPath, object rep string temporary = reportPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { - File.WriteAllText(temporary, JsonSerializer.Serialize(report, JsonOptions), new UTF8Encoding(false)); + File.WriteAllText(temporary, SerializeReport(report), new UTF8Encoding(false)); File.Move(temporary, reportPath, overwrite: true); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index 7245cf27..0a3ffc43 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -108,6 +108,8 @@ replace a supported parameter in a local Revit 2020-2027 project replace a supported parameter on a type in a local Revit 2020-2027 family edit-parameters apply an ordered batch of supported parameter assignments and clears atomically + audit-shared-parameters [--report ] + compare shared parameter definitions by GUID and write a JSON report coverage [--report ] [--top ] (first argument) count the records of the partition streams that the class schema of the file walks to their last byte, per channel and class; writes nothing but the report @@ -189,6 +191,7 @@ internal static int Main(string[] args) if (args[0] == "set-parameter") return RvtIO.Cli.SetParameterCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "set-family-parameter") return RvtIO.Cli.SetParameterCommand.Run(args[1..], Console.Out, Console.Error, familyFile: true); if (args[0] == "edit-parameters") return RvtIO.Cli.SetParameterCommand.RunBatch(args[1..], Console.Out, Console.Error); + if (args[0] == "audit-shared-parameters") return RvtIO.Cli.SharedParameterAuditCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "coverage") return RvtIO.Cli.CoverageCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "info") return RvtIO.Cli.InfoCommand.Run(args[1..], Console.Out, Console.Error); if (args[0] == "diff") return RvtIO.Cli.DiffCommand.Run(args[1..], Console.Out, Console.Error); diff --git a/src/RvtIO.Cli/SharedParameterAudit.cs b/src/RvtIO.Cli/SharedParameterAudit.cs new file mode 100644 index 00000000..69109bef --- /dev/null +++ b/src/RvtIO.Cli/SharedParameterAudit.cs @@ -0,0 +1,144 @@ +using System.Globalization; +using System.Text; +using RvtIO.BuiltIns; +using RvtIO.Diagnostics; + +namespace RvtIO.Cli; + +internal static class SharedParameterAudit +{ + internal sealed record FopParameter(int Line, Guid Guid, string Name, string DataType, long? DataCategory, string? Description); + internal sealed record Comparison(Guid Guid, SharedParameterInventory.Definition[] Model, FopParameter[] Fop, string[] Findings); + internal sealed record NameCollision(string Name, Guid[] Guids); + internal sealed record Report(string Schema, Comparison[] Parameters, NameCollision[] NameCollisions, + IReadOnlyList UnreadableDefinitions); + + internal static List ReadFop(string path) + { + byte[] bytes = File.ReadAllBytes(path); + using var reader = new StringReader(DecodeFop(bytes)); + return ParseFop(reader); + } + + private static string DecodeFop(ReadOnlySpan bytes) + { + if (bytes.StartsWith(new byte[] { 0xff, 0xfe })) + return new UnicodeEncoding(false, false, true).GetString(bytes[2..]); + if (bytes.StartsWith(new byte[] { 0xfe, 0xff })) + return new UnicodeEncoding(true, false, true).GetString(bytes[2..]); + if (bytes.StartsWith(new byte[] { 0xef, 0xbb, 0xbf })) + bytes = bytes[3..]; + return new UTF8Encoding(false, true).GetString(bytes); + } + + internal static List ParseFop(TextReader reader) + { + var parameters = new List(); + var columns = new Dictionary(StringComparer.Ordinal); + bool header = false; + int number = 0; + while (reader.ReadLine() is { } line) + { + number++; + if (string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith('#')) continue; + + string[] cells = line.Split('\t'); + string kind = cells[0].Trim(); + if (kind is "*META" or "META" or "*GROUP" or "GROUP") continue; + if (kind == "*PARAM") + { + if (header) + throw Invalid(number, "duplicate *PARAM header."); + for (int column = 1; column < cells.Length; column++) + if (!columns.TryAdd(cells[column].Trim(), column)) + throw Invalid(number, $"duplicate *PARAM column '{cells[column]}'."); + if (!columns.ContainsKey("GUID") || !columns.ContainsKey("NAME") || + !columns.ContainsKey("DATATYPE") || !columns.ContainsKey("DATACATEGORY")) + throw Invalid(number, "the *PARAM header must declare GUID, NAME, DATATYPE, and DATACATEGORY."); + header = true; + continue; + } + if (kind != "PARAM" || !header) + throw Invalid(number, "expected a *PARAM header or a tab-delimited PARAM row."); + + string? Cell(string column) => columns.TryGetValue(column, out int index) && index < cells.Length + ? cells[index] : null; + + if (!Guid.TryParse(Cell("GUID")?.Trim(), out var guid) || guid == Guid.Empty) + throw Invalid(number, "invalid shared parameter GUID."); + string? name = Cell("NAME"); + string? type = Cell("DATATYPE")?.Trim(); + string? dataCategory = Cell("DATACATEGORY")?.Trim(); + if (string.IsNullOrWhiteSpace(name) || string.IsNullOrEmpty(type) || dataCategory == null) + throw Invalid(number, "the name, data type, or data category column is missing."); + + long? category = null; + if (type.Equals("FAMILYTYPE", StringComparison.OrdinalIgnoreCase)) + { + if (!long.TryParse(dataCategory, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long id) || id >= 0) + throw Invalid(number, "FAMILYTYPE requires a negative DATACATEGORY ID."); + category = id; + } + parameters.Add(new FopParameter(number, guid, name, type, category, Cell("DESCRIPTION"))); + } + if (!header) + throw Invalid(number, "missing *PARAM header."); + return parameters; + } + + private static InvalidDataException Invalid(int line, string message) => + new($"Invalid shared parameter file at line {line}: {message}"); + + internal static Report Compare(SharedParameterInventory.Result inventory, IReadOnlyList parameters) + { + var model = inventory.Definitions.ToLookup(p => p.Guid); + var fop = parameters.ToLookup(p => p.Guid); + var comparisons = new List(); + foreach (Guid guid in model.Select(group => group.Key).Union(fop.Select(group => group.Key)).Order()) + { + var existing = model[guid].OrderBy(p => p.ElementId).ToArray(); + var standard = fop[guid].OrderBy(p => p.Line).ToArray(); + var findings = new List(); + if (existing.Length == 0) + findings.Add(inventory.Issues.Count == 0 ? "fop-only" : "not-confirmed-in-model"); + if (standard.Length == 0) + findings.Add("model-only"); + if (existing.Length > 1) + findings.Add("duplicate-model-guid"); + if (standard.Length > 1) + findings.Add("duplicate-fop-guid"); + if (existing is [var left] && standard is [var right]) + ComparePair(left, right, findings); + comparisons.Add(new(guid, existing, standard, [.. findings])); + } + + var names = inventory.Definitions.Select(p => (p.Name, p.Guid)).Concat(parameters.Select(p => (p.Name, p.Guid))); + var collisions = names.GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase) + .Select(group => new NameCollision(group.Select(p => p.Name).Order(StringComparer.Ordinal).First(), + group.Select(p => p.Guid).Distinct().Order().ToArray())) + .Where(group => group.Guids.Length > 1).OrderBy(group => group.Name, StringComparer.Ordinal).ToArray(); + return new("rvtio-shared-parameter-audit/1", [.. comparisons], collisions, inventory.Issues); + } + + private static void ComparePair(SharedParameterInventory.Definition model, FopParameter fop, List findings) + { + if (!string.Equals(model.Name, fop.Name, StringComparison.Ordinal)) findings.Add("name-mismatch"); + if (fop.Description != null) + { + if (model.Description == null) findings.Add("description-unverified"); + else if (!string.Equals(model.Description, fop.Description, StringComparison.Ordinal)) findings.Add("description-mismatch"); + } + + string type = fop.DataType.ToUpperInvariant(); + if (type == "TIME") type = "TIMEINTERVAL"; + if (model.DataType == null || (type.FromSharedDataType() == ParameterType.Invalid && type is not ("SPEED" or "TIMEINTERVAL"))) + findings.Add("type-unverified"); + else if (model.DataType != type) + findings.Add("incompatible-type"); + else if (type == "FAMILYTYPE") + { + if (model.DataCategory == null) findings.Add("type-unverified"); + else if (model.DataCategory != fop.DataCategory) findings.Add("incompatible-type"); + } + } +} diff --git a/src/RvtIO.Cli/SharedParameterAuditCommand.cs b/src/RvtIO.Cli/SharedParameterAuditCommand.cs new file mode 100644 index 00000000..a1ecd786 --- /dev/null +++ b/src/RvtIO.Cli/SharedParameterAuditCommand.cs @@ -0,0 +1,90 @@ +using System.Text; +using RvtIO.Diagnostics; +using RvtIO.Internal; + +namespace RvtIO.Cli; + +internal static class SharedParameterAuditCommand +{ + private const string Usage = "Usage: rvtio audit-shared-parameters [--report ]"; + + internal static int Run(string[] args, TextWriter output, TextWriter error) + { + if (args is ["--help"] or ["-h"]) + { + output.WriteLine(Usage); + return RvtExitCodes.Success; + } + + string? model = null, fop = null, reportPath = null; + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + if (arg == "--report") + { + if (reportPath != null || i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + return UsageError(error, "--report takes one path and can be given once."); + reportPath = args[++i]; + } + else if (arg.StartsWith("--", StringComparison.Ordinal)) + return UsageError(error, $"Unknown option: {arg}."); + else if (model == null) + model = arg; + else if (fop == null) + fop = arg; + else + return UsageError(error, "Expected a model and a shared parameter file."); + } + + if (string.IsNullOrWhiteSpace(model) || string.IsNullOrWhiteSpace(fop) || + reportPath != null && string.IsNullOrWhiteSpace(reportPath)) + return UsageError(error, "A file path is missing or empty."); + + try + { + model = Path.GetFullPath(model); + fop = Path.GetFullPath(fop); + if (reportPath != null) + { + reportPath = Path.GetFullPath(reportPath); + if (Directory.Exists(reportPath) || FileIdentity.SameFile(reportPath, model) || FileIdentity.SameFile(reportPath, fop)) + return UsageError(error, "--report must name a file distinct from both inputs."); + } + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException or UnauthorizedAccessException) + { + return UsageError(error, ex.Message); + } + + SharedParameterAudit.Report report; + try + { + var standard = SharedParameterAudit.ReadFop(fop); + report = SharedParameterAudit.Compare(SharedParameterInventory.Read(model), standard); + } + catch (RvtLimitException ex) + { + error.WriteLine($"error: {ex.Message}"); + return RvtExitCodes.LimitExceeded; + } + catch (Exception ex) when (ex is RvtInputException or InvalidDataException or IOException or UnauthorizedAccessException or DecoderFallbackException) + { + error.WriteLine($"error: {ex.Message}"); + return RvtExitCodes.InputError; + } + + if (reportPath == null) + output.WriteLine(DowngradeCommand.SerializeReport(report)); + else if (DowngradeCommand.WriteReport(error, reportPath, report, RvtExitCodes.Success) != RvtExitCodes.Success) + return RvtExitCodes.Usage; + + return report.UnreadableDefinitions.Count == 0 ? RvtExitCodes.Success : RvtExitCodes.PartialRead; + } + + private static int UsageError(TextWriter error, string message) + { + error.WriteLine(message); + error.WriteLine(Usage); + return RvtExitCodes.Usage; + } +} diff --git a/src/RvtIO/Diagnostics/SharedParameterInventory.cs b/src/RvtIO/Diagnostics/SharedParameterInventory.cs new file mode 100644 index 00000000..11eb633b --- /dev/null +++ b/src/RvtIO/Diagnostics/SharedParameterInventory.cs @@ -0,0 +1,192 @@ +using System.Buffers.Binary; +using System.Globalization; +using OpenMcdf; +using RvtIO.BuiltIns; +using RvtIO.Parsing; +using RvtIO.Writing; + +namespace RvtIO.Diagnostics; + +internal static class SharedParameterInventory +{ + internal sealed record Definition(long ElementId, Guid Guid, string Name, string? Description, + string? DataType, long? DataCategory, string DefinitionClass, string? SpecTypeId); + + internal sealed record Issue(long ElementId, string Code); + + internal sealed record Result(IReadOnlyList Definitions, IReadOnlyList Issues); + + private static readonly Dictionary EngineeringSpecs = new(StringComparer.Ordinal) + { + ["autodesk.spec.aec.electrical:apparentPower"] = UnitType.UT_Electrical_Apparent_Power, + ["autodesk.spec.aec.electrical:current"] = UnitType.UT_Electrical_Current, + ["autodesk.spec.aec.electrical:potential"] = UnitType.UT_Electrical_Potential, + ["autodesk.spec.aec.electrical:power"] = UnitType.UT_Electrical_Power, + ["autodesk.spec.aec.electrical:wattage"] = UnitType.UT_Electrical_Wattage, + ["autodesk.spec.aec.hvac:pressure"] = UnitType.UT_HVAC_Pressure, + ["autodesk.spec.aec.piping:flow"] = UnitType.UT_Piping_Flow, + ["autodesk.spec.aec.piping:pipeSize"] = UnitType.UT_PipeSize, + ["autodesk.spec.aec.piping:pressure"] = UnitType.UT_Piping_Pressure, + ["autodesk.spec.aec.structural:moment"] = UnitType.UT_Moment, + ["autodesk.spec.aec.structural:reinforcementLength"] = UnitType.UT_Reinforcement_Length, + }; + + internal static Result Read(string path) + { + RvtContainerCheck.Verify(path); + using var root = RootStorage.OpenRead(path); + var document = TfSchemaReader.Read(root) ?? throw Unreadable("Formats/Latest could not be read."); + var schema = new FormatsSchema(document); + if (schema.IdOf("ParamElemExternal") is null) + throw Unreadable("The class table has no shared parameter definition class."); + var census = RecordRouting.Begin(schema, out string? failure) + ?? throw Unreadable($"The partition layout could not be identified ({failure})."); + if (PagedGzipStream.Read(root, "Global", "ElemTable") is not { } table + || ElemTableLayout.TryParse(table, schema) is not { } elements) + throw Unreadable("Global/ElemTable could not be read."); + if (!root.TryOpenStorage("Partitions", out var partitions)) + throw Unreadable("The file has no Partitions storage."); + var streams = partitions.EnumerateEntries() + .Where(e => e.Type == EntryType.Stream && int.TryParse(e.Name, NumberStyles.None, CultureInfo.InvariantCulture, out _)) + .OrderBy(e => int.Parse(e.Name, CultureInfo.InvariantCulture)).ToArray(); + if (streams.Length == 0) + throw Unreadable("The file has no numbered partition streams."); + + var active = elements.Select(row => row.Id).ToHashSet(); + var walker = new WideBlockWalker(document, CaptureKey, ["ForgeTypeId"]); + var candidates = new Dictionary>(); + foreach (var entry in streams) + { + int number = int.Parse(entry.Name, CultureInfo.InvariantCulture); + if (entry.Length > Array.MaxLength) + throw new RvtLimitException(new($"Partitions/{entry.Name}", "array-length", entry.Length, false, + $"Partition {entry.Name} exceeds the maximum array length.")); + using var stream = partitions.OpenStream(entry.Name); + var raw = new byte[entry.Length]; + stream.ReadExactly(raw); + + void Visit(PartitionFraming.Record record) + { + if (record.Block != 0 || record.Channel != 102 || record.Owner > long.MaxValue + || record.Body.Length < sizeof(ushort) || !active.Contains((long)record.Owner)) + return; + int classId = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + if (!walker.IsA(classId, "ParamElemExternal")) + return; + long id = (long)record.Owner; + if (!candidates.TryGetValue(id, out var copies)) + candidates[id] = copies = []; + copies.Add((number, ReadDefinition(walker, id, classId, record.Body.ToArray()))); + } + + bool exact = streams.Length == 1 + ? PartitionFraming.Walk(raw, census.Tags, census.IdWidth, Visit, out failure, out _) + : RecordRouting.Collect(census, number, raw, out failure, Visit); + if (!exact) + throw Unreadable($"Partition {entry.Name} could not be read ({failure})."); + } + + var current = new Dictionary(); + if (streams.Length > 1 && candidates.Keys.Any(id => census.Holders[(ulong)id].Count > 1) && + PagedGzipStream.Read(root, "Global", "DocumentIncrementTable") is { } increments && + DocumentIncrementTable.TryParse(increments, schema, out _) is { } routes) + current = RecordRouting.Current(census, elements, routes); + + var definitions = new List(); + var issues = new List(); + foreach (var (id, copies) in candidates.OrderBy(pair => pair.Key)) + { + bool missingCopy = false; + if (current.TryGetValue((ulong)id, out int number)) + copies.RemoveAll(copy => copy.Partition != number); + else if (census.Holders.TryGetValue((ulong)id, out var holders)) + missingCopy = holders.Any(holder => copies.All(copy => copy.Partition != holder)); + if (copies.Count == 0) continue; + if (missingCopy || copies.Any(copy => copy.Definition != copies[0].Definition)) + { + issues.Add(new(id, "ambiguous-record")); + continue; + } + if (copies[0].Definition is { } definition) + definitions.Add(definition); + else + issues.Add(new(id, "unreadable-definition")); + } + return new(definitions, issues); + } + + private static RvtInputException Unreadable(string message) => new("truncated-or-damaged", message); + + private static string? CaptureKey(SchemaClass declaring, SchemaField field) => (declaring.Name, field.Name) switch + { + ("Element", "m_id") or + ("ParamElem", "m_pParamDef" or "m_description") or + ("ParamElemExternal", "m_externalParamKey") or + ("ParamDef", "m_caption" or "m_paramElemId") or + ("ParamDefValue", "m_unitType" or "m_specTypeId") or + ("ParamDefFamType", "m_categoryId") => declaring.Name + "." + field.Name, + _ => null, + }; + + private static Definition? ReadDefinition(WideBlockWalker walker, long id, int classId, byte[] body) + { + var walked = walker.Run(body, 0, body.Length, classId); + if (!walked.Exact || walked.EmptyEntityAt >= 0 || + Capture(walked, "Element.m_id")?.Integer != id || + Capture(walked, "ParamElemExternal.m_externalParamKey")?.Text is not string key || + !Guid.TryParseExact(key, "D", out Guid guid) || guid == Guid.Empty || + Capture(walked, "ParamElem.m_pParamDef") is not { Integer: > 0, QueuePosition: >= 0 } pointer || + pointer.QueuePosition >= walked.Queue.Count) + return null; + int slot = pointer.QueuePosition; + int defClass = walked.Queue[slot]; + if (!walker.IsA(defClass, "ParamDef") || + Capture(walked, "ParamDef.m_paramElemId", slot)?.Integer != id || + Capture(walked, "ParamDef.m_caption", slot)?.Text is not { Length: > 0 } name) + return null; + + string className = walker.Class(defClass)!.Name; + string? spec = Capture(walked, "ParamDefValue.m_specTypeId", slot)?.Text; + string? dataType = className switch + { + "ParamDefString" => "TEXT", + "ParamDefTextBrowseEdit" => "MULTILINETEXT", + "ParamDefURL" => "URL", + "ParamDefYesNo" or "RbsParamDefBool" => "YESNO", + "ParamDefInt" => "INTEGER", + "ParamDefNoOfPoles" => "NOOFPOLES", + "ParamDefMaterialBrowse" => "MATERIAL", + "ParamDefImageSymbolBrowseEdit" => "IMAGE", + "ParamDefFixtureUnit" => "FIXTUREUNIT", + "ElectricalLoadClassificationParamDef" => "LOADCLASSIFICATION", + "ParamDefFamType" or "ParamDefFamTypeFamParm" => "FAMILYTYPE", + "ParamDefValue" => MeasuredDataType(walked, slot, spec), + _ => null, + }; + long? category = Capture(walked, "ParamDefFamType.m_categoryId", slot)?.Integer; + return new(id, guid, name, Capture(walked, "ParamElem.m_description")?.Text, + dataType, category is < 0 ? category : null, className, spec); + } + + private static string? MeasuredDataType(WideBlockWalker.Walk walked, int slot, string? spec) + { + UnitType? unit = ParameterMeasurement.Spec(walked, slot, includeCurrency: true, includeAdditional: true); + if (unit == null && spec != null && EngineeringSpecs.TryGetValue(UnitSchemaEvaluator.DisplayNameKey(spec), out var engineering)) + unit = engineering; + if (unit == null && Capture(walked, "ParamDefValue.m_unitType", slot) is { Integer: >= 0 and <= int.MaxValue } legacy && + EngineeringSpecs.ContainsValue((UnitType)legacy.Integer)) + unit = (UnitType)legacy.Integer; + + return unit switch + { + UnitType.UT_Speed => "SPEED", + UnitType.UT_TimeInterval => "TIMEINTERVAL", + UnitType known when known.TryGetParameterType(out var parameter) => parameter.ToSharedDataType(), + _ => null, + }; + } + + private static WideBlockWalker.Capture? Capture(WideBlockWalker.Walk walked, string key, int slot = -1) => + walked.Captures.Where(c => c.Key == key && (slot < 0 ? c.AtRoot : c.QueueIndex == slot)).ToArray() + is [var value] ? value : null; +} diff --git a/src/RvtIO/Parsing/RecordRouting.cs b/src/RvtIO/Parsing/RecordRouting.cs index 7dba263c..93fd7bc7 100644 --- a/src/RvtIO/Parsing/RecordRouting.cs +++ b/src/RvtIO/Parsing/RecordRouting.cs @@ -45,7 +45,8 @@ internal sealed class Census } /// Walks one partition stream into the census; false (with the reason) when its framing does not hold. - internal static bool Collect(Census census, int partition, byte[] raw, out string? failure) + internal static bool Collect(Census census, int partition, byte[] raw, out string? failure, + Action? visit = null) { var lengths = new List(); var holders = new List<(ulong Owner, long Offset, int Length)>(); @@ -58,6 +59,7 @@ internal static bool Collect(Census census, int partition, byte[] raw, out strin { if (r.Owner == (census.IdWidth == 8 ? ulong.MaxValue : uint.MaxValue)) return; if (r.Block != 0) { if (r.Channel == 101) keyed++; return; } + visit?.Invoke(r); holders.Add((r.Owner, r.Offset, r.Item.Length)); if (!hashers.TryGetValue(r.Owner, out var hasher)) hashers[r.Owner] = hasher = System.Security.Cryptography.IncrementalHash.CreateHash(System.Security.Cryptography.HashAlgorithmName.SHA256); diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 377b469b..8fb439cc 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -1613,7 +1613,8 @@ private List DecompressPartitions(RootStorage root, TextWriter? diag, bool collectFamilyStorage = false, IProgress? progress = null) { staleCopiesRemoved = false; - var partStor = root.OpenStorage("Partitions"); + if (!root.TryOpenStorage("Partitions", out var partStor)) + throw new RvtInputException("truncated-or-damaged", "The file has no Partitions storage."); var partEntries = partStor.EnumerateEntries() .Where(e => e.Type == EntryType.Stream) .OrderByDescending(e => e.Length) diff --git a/src/RvtIO/Writing/PageCodec.cs b/src/RvtIO/Writing/PageCodec.cs index 6e587d5e..4af84602 100644 --- a/src/RvtIO/Writing/PageCodec.cs +++ b/src/RvtIO/Writing/PageCodec.cs @@ -13,7 +13,7 @@ internal enum PageCheckStatus BadPage, /// The check bytes of the last, short page do not match its content. BadTail, - /// The length of the last, short page is not one this codec writes, so it was not checked. + /// The stored length of the last page fits none of the verified layouts. UnsupportedTail, } @@ -25,17 +25,16 @@ internal enum PageCheckStatus /// Writer of the page layer of the paged streams (Partitions, Formats/Latest, Global): the layout that /// reads, with the check bytes of every page. /// -/// Every page holds 64,896 payload bytes and 353 check bytes (65,249 bytes in all). Read as a little-endian bit string, a page +/// A full page holds 64,896 payload bytes and 353 check bytes (65,249 bytes in all). Read as a little-endian bit string, a page /// is split into D interleaved lanes: bit k belongs to lane k mod D. Each lane is a Hamming code of 2,047 bits with the generator /// y^11 + y^9 + 1, holding 2,036 data bits and 11 parity bits. A full page has D = 255 lanes: its 519,168 payload bits and 12 zero /// bits make the 2,036 data bits of each lane, and the 2,805 parity bits come next, followed by 7 zero bits. This is the cyclic /// code with generator x^2805 + x^2295 + 1 (the lane generator in y = x^255). /// -/// The last page of a stream may be shorter. This codec writes it in one form only, the form measured on the long last pages of -/// the streams of the sample files: D is the smallest odd number of lanes whose data bits hold the content and two zero bytes of -/// slack, the data bits not used by the content are written as zero (the files keep a few set bits at the end of that region, which -/// is not reproduced), and the parity bits follow the data bits directly. The stored page is ceil(D * 2,047 / 8) bytes long. Shorter last pages are stored differently (other lane codes), and a last page that holds exactly -/// 64,896 bytes does not follow this rule; neither is written (see ). +/// Short pages use the first measured code whose lane capacity holds the content and its reserved bits. At 65 lanes the +/// code can omit low-order zeros, which still take part in the parity calculation. Larger lane counts use full-length lanes. +/// The long last-page form uses the smallest odd lane count that holds the content and two zero bytes of slack. +/// Unused data bits are written as zero. See for empty or exact-full-page tails. /// /// only looks at the first two bytes of the check bytes of a page and removes them; it does not read the /// parity bits, so a flipped payload bit is found there only through the CRC of the gzip member. checks the parity bits. @@ -46,9 +45,16 @@ internal static class PageCodec private const int ParityBitsPerLane = 11; private const int FullPageLanes = 255; private const int SlackBytes = 2; + private const int ShortenedTailLanes = 65; + private const int SmallestVerifiedTailSize = 82; - /// Shortest last page (content bytes) written. Below it the stored form differs (fewer lanes, some of them shortened). - internal const int MinTailLength = 16_541; + // The lane limits and reserved bits follow the shapes measured on Revit-saved pages. Some reserved-bit counts + // give identical shapes at the measured lengths. Each generator is y^ParityBits + y^Tap + 1. + private static readonly (int ParityBits, int Tap, int MaxLanes, int ReservedBits)[] ShortTailCodes = + [(4, 3, 77, 4), (5, 3, 79, 4), (6, 5, 77, 4), (7, 6, 85, 5), (9, 5, 81, 7), (11, 9, 65, 9)]; + + /// Shortest content length encoded with the measured short-page codes. + internal const int MinTailLength = 44; /// Longest last page (content bytes) written: a full page minus one byte. internal const int MaxTailLength = PagedGzipStream.PageDataLength - 1; @@ -64,8 +70,8 @@ internal static byte[] Encode(ReadOnlySpan content) $"The last page would hold {tailLength} bytes; only {MinTailLength} to {MaxTailLength} bytes are written. " + "Append the zero bytes of NaturalPadding to the content first."); int pages = (content.Length - tailLength) / PagedGzipStream.PageDataLength; - int lanes = TailLanes(tailLength); - var stored = new byte[checked(pages * PagedGzipStream.PageStride + TailStoredLength(lanes))]; + var (lanes, codeBits, parityBits, tap) = TailLayout(tailLength); + var stored = new byte[checked(pages * PagedGzipStream.PageStride + (lanes * codeBits + 7) / 8)]; for (int page = 0; page < pages; page++) { Span block = stored.AsSpan(page * PagedGzipStream.PageStride, PagedGzipStream.PageStride); @@ -74,7 +80,7 @@ internal static byte[] Encode(ReadOnlySpan content) } Span last = stored.AsSpan(pages * PagedGzipStream.PageStride); content[(pages * PagedGzipStream.PageDataLength)..].CopyTo(last); - Seal(last, lanes); + Seal(last, lanes, codeBits, parityBits, tap); return stored; } @@ -120,14 +126,81 @@ internal static PageCheck Verify(ReadOnlySpan stored) int rest = stored.Length - at; if (rest == 0) return new PageCheck(PageCheckStatus.Valid, page); int lanes = LanesOfStoredTail(rest); - if (lanes == 0) return new PageCheck(PageCheckStatus.UnsupportedTail, page); + if (lanes == 0) return new PageCheck(CheckShortTail(stored[at..]), page); return new PageCheck(IsSealed(stored[at..], lanes) ? PageCheckStatus.Valid : PageCheckStatus.BadTail, page); } + private static PageCheckStatus CheckShortTail(ReadOnlySpan tail) + { + if (tail.Length < SmallestVerifiedTailSize || tail.Length >= TailStoredLength(ShortenedTailLanes + 2)) + return PageCheckStatus.UnsupportedTail; + + int storedBits = tail.Length * 8; + int shortenedCodeBits = storedBits / ShortenedTailLanes; + bool fitsShortenedLanes = storedBits % ShortenedTailLanes <= 7; + PageCheckStatus status = PageCheckStatus.UnsupportedTail; + // A stored byte length can fit several layouts. Check them without inferring Revit's choice from the length alone. + foreach (var (parityBits, tap, _, _) in ShortTailCodes) + { + int fullCodeBits = (1 << parityBits) - 1; + int fullLanes = storedBits / fullCodeBits; + if (fullLanes is >= ShortenedTailLanes and <= FullPageLanes && (fullLanes & 1) != 0 && + storedBits % fullCodeBits <= 7) + { + if (IsShortTailSealed(tail, fullLanes, fullCodeBits, parityBits, tap)) return PageCheckStatus.Valid; + status = PageCheckStatus.BadTail; + } + + if (!fitsShortenedLanes || shortenedCodeBits <= parityBits || shortenedCodeBits >= fullCodeBits) continue; + if (IsShortTailSealed(tail, ShortenedTailLanes, shortenedCodeBits, parityBits, tap)) return PageCheckStatus.Valid; + status = PageCheckStatus.BadTail; + } + return status; + } + + private static bool IsShortTailSealed(ReadOnlySpan tail, int lanes, int codeBits, int parityBits, int tap) + { + int padding = tail.Length * 8 - lanes * codeBits; + if ((tail[^1] >> (8 - padding)) != 0) return false; + + int dataEnd = lanes * (codeBits - parityBits); + int words = (lanes + 63) >> 6; + Span planes = stackalloc ulong[parityBits * words]; + int head = CalculateParity(tail, lanes, codeBits, parityBits, tap, planes, words); + for (int bit = 0; bit < parityBits; bit++) + { + int slot = (head + bit) % parityBits; + for (int word = 0; word < words; word++) + { + int firstLane = word * 64; + ulong mask = ulong.MaxValue >> (64 - Math.Min(64, lanes - firstLane)); + if (planes[slot * words + word] != (Read64(tail, dataEnd + (long)bit * lanes + firstLane) & mask)) + return false; + } + } + return true; + } + // Content bytes of the last page: the last 1 to 64,896 bytes (0 only for empty content). private static int TailLength(int contentLength) => contentLength == 0 ? 0 : (contentLength - 1) % PagedGzipStream.PageDataLength + 1; + private static (int Lanes, int CodeBits, int ParityBits, int Tap) TailLayout(int length) + { + foreach (var (parityBits, tap, maxLanes, reservedBits) in ShortTailCodes) + { + int fullCodeBits = (1 << parityBits) - 1; + int capacity = fullCodeBits - parityBits; + int dataBits = length * 8 + reservedBits; + if (dataBits > maxLanes * capacity) continue; + if (dataBits <= ShortenedTailLanes * capacity) + return (ShortenedTailLanes, (dataBits + ShortenedTailLanes - 1) / ShortenedTailLanes + parityBits, parityBits, tap); + int lanes = ((dataBits + capacity - 1) / capacity) | 1; + return (lanes, fullCodeBits, parityBits, tap); + } + return (TailLanes(length), LaneDataBits + ParityBitsPerLane, ParityBitsPerLane, 9); + } + // Smallest odd lane count whose data bits hold the content and the slack. private static int TailLanes(int tailLength) => (int)((8L * (tailLength + SlackBytes) + LaneDataBits - 1) / LaneDataBits) | 1; @@ -138,7 +211,7 @@ private static int TailLanes(int tailLength) => // (a stored page of 65,249 bytes is a full page and is checked as one). private static int LanesOfStoredTail(int length) { - for (int lanes = TailLanes(MinTailLength); lanes < FullPageLanes; lanes += 2) + for (int lanes = ShortenedTailLanes + 2; lanes < FullPageLanes; lanes += 2) if (TailStoredLength(lanes) == length) return lanes; return 0; } @@ -150,41 +223,21 @@ private static bool IsSealed(ReadOnlySpan block, int lanes) return copy.AsSpan().SequenceEqual(block); } - /// Clears every bit of the block from the end of the data bits on, then writes the parity bits there. The data bits - /// are the first lanes * 2,036 bits; the block holds lanes * 2,047 bits rounded up to whole bytes. - private static void Seal(Span block, int lanes) + /// Clears the bits after the data, then writes the parity planes and zero byte padding. + private static void Seal(Span block, int lanes, int codeBits = LaneDataBits + ParityBitsPerLane, + int parityBits = ParityBitsPerLane, int tap = 9) { - long dataBits = (long)lanes * LaneDataBits; + long dataBits = (long)lanes * (codeBits - parityBits); int wholeBytes = (int)(dataBits >> 3), extraBits = (int)(dataBits & 7); if (extraBits != 0) block[wholeBytes++] &= (byte)((1 << extraBits) - 1); block[wholeBytes..].Clear(); - // Per lane the parity is (data(y) * y^11) mod (y^11 + y^9 + 1), by long division from the highest data bit down. - // The remainder coefficients are kept as 11 planes, each holding that coefficient for all lanes (bit j = lane j); - // plane i sits in slot (head + i) mod 11, so shifting the remainder up one place only moves head. int words = (lanes + 63) >> 6; - Span planes = stackalloc ulong[ParityBitsPerLane * words]; - planes.Clear(); - int head = 0; - for (int step = 0; step < LaneDataBits + ParityBitsPerLane; step++) + Span planes = stackalloc ulong[parityBits * words]; + int head = CalculateParity(block, lanes, codeBits, parityBits, tap, planes, words); + for (int plane = 0; plane < parityBits; plane++) { - int slot = (head + ParityBitsPerLane - 1) % ParityBitsPerLane; // the plane that leaves through y^11 - Span carry = planes.Slice(slot * words, words); - Span nine = planes.Slice((slot + 9) % ParityBitsPerLane * words, words); - for (int w = 0; w < words; w++) nine[w] ^= carry[w]; // y^11 = y^9 + 1 - if (step < LaneDataBits) - { - long offset = (long)lanes * (LaneDataBits - 1 - step); // bit k = j + lanes * t is lane j, position t - for (int w = 0; w < words; w++) carry[w] ^= Read64(block, offset + 64L * w); - int lastBits = lanes & 63; - if (lastBits != 0) carry[words - 1] &= (1UL << lastBits) - 1; - } - head = slot; - } - - for (int plane = 0; plane < ParityBitsPerLane; plane++) - { - int slot = (head + plane) % ParityBitsPerLane; + int slot = (head + plane) % parityBits; for (int w = 0; w < words; w++) { ulong bits = planes[slot * words + w]; @@ -198,6 +251,32 @@ private static void Seal(Span block, int lanes) } } + private static int CalculateParity(ReadOnlySpan block, int lanes, int codeBits, int parityBits, int tap, + Span planes, int words) + { + // Divide the interleaved lane polynomials together. After the data, roll in the omitted zeros and the parity degree. + int dataBitsPerLane = codeBits - parityBits; + int fullCodeBits = (1 << parityBits) - 1; + planes.Clear(); + int head = 0; + for (int step = 0; step < fullCodeBits; step++) + { + int slot = (head + parityBits - 1) % parityBits; + Span carry = planes.Slice(slot * words, words); + Span tapped = planes.Slice((slot + tap) % parityBits * words, words); + for (int w = 0; w < words; w++) tapped[w] ^= carry[w]; + if (step < dataBitsPerLane) + { + long offset = (long)lanes * (dataBitsPerLane - 1 - step); + for (int w = 0; w < words; w++) carry[w] ^= Read64(block, offset + 64L * w); + int lastBits = lanes & 63; + if (lastBits != 0) carry[words - 1] &= (1UL << lastBits) - 1; + } + head = slot; + } + return head; + } + // The 64 bits that start at this bit offset (bit i of byte j has index 8 * j + i); bits past the end read as zero. private static ulong Read64(ReadOnlySpan bytes, long bitOffset) { diff --git a/tests/RvtIO.Tests/PageCodecReference.cs b/tests/RvtIO.Tests/PageCodecReference.cs index 78ac537a..649848d4 100644 --- a/tests/RvtIO.Tests/PageCodecReference.cs +++ b/tests/RvtIO.Tests/PageCodecReference.cs @@ -8,27 +8,100 @@ namespace RvtIO.Tests; /// with the lane and bit-plane implementation of the codec. internal static class PageCodecReference { + // Generator coefficients recovered by comparing the parity with streams saved by Revit. + private static readonly (int ParityBits, int Generator)[] ShortTailCodes = + [(4, 0x19), (5, 0x29), (6, 0x61), (7, 0xC1), (9, 0x221), (11, 0xA01)]; + + internal const int SmallestMeasuredTailSize = 82; + internal const int FirstLongTailSize = (67 * 2047 + 7) / 8; + + internal readonly record struct ShortTailLayout(int Lanes, int CodeBits, int ParityBits, int Generator) + { + internal int DataEnd => Lanes * (CodeBits - ParityBits); + internal int ParityEnd => Lanes * CodeBits; + } + + internal static List ShortTailLayouts(ReadOnlySpan stored) + { + var matches = new List(); + if (stored.Length is < SmallestMeasuredTailSize or >= FirstLongTailSize) return matches; + + // Enumerate the shapes observed on disk without assuming at which payload size Revit selects a code. + int storedBits = stored.Length * 8; + for (int lanes = 65; lanes <= 255; lanes += 2) + { + int codeBits = storedBits / lanes; + if (storedBits % lanes > 7) continue; + foreach (var (parityBits, generator) in ShortTailCodes) + { + int fullCodeBits = (1 << parityBits) - 1; + if (codeBits <= parityBits || codeBits > fullCodeBits || lanes != 65 && codeBits != fullCodeBits) + continue; + var layout = new ShortTailLayout(lanes, codeBits, parityBits, generator); + if (MatchesShortTail(stored, layout)) matches.Add(layout); + } + } + return matches; + } + + internal static bool MatchesShortTail(ReadOnlySpan stored, ShortTailLayout layout) + { + if (stored.Length != (layout.ParityEnd + 7) / 8) return false; + int paddingBits = stored.Length * 8 - layout.ParityEnd; + if ((stored[^1] >> (8 - paddingBits)) != 0) return false; + + int top = 1 << layout.ParityBits; + int shortenedBits = top - 1 - layout.CodeBits; + for (int lane = 0; lane < layout.Lanes; lane++) + { + int remainder = 0; + for (int bit = layout.DataEnd - layout.Lanes + lane; bit >= 0; bit -= layout.Lanes) + remainder = AppendBit(remainder, Bit(stored, bit), top, layout.Generator); + + // The omitted zero coefficients are at the low end of the data polynomial, before multiplication by y^p. + for (int i = 0; i < shortenedBits + layout.ParityBits; i++) + remainder = AppendBit(remainder, 0, top, layout.Generator); + + for (int bit = layout.DataEnd + lane; bit < layout.ParityEnd; bit += layout.Lanes) + { + if ((remainder & 1) != Bit(stored, bit)) return false; + remainder >>= 1; + } + } + return true; + } + + private static int Bit(ReadOnlySpan bytes, int bit) => (bytes[bit >> 3] >> (bit & 7)) & 1; + + private static int AppendBit(int remainder, int bit, int top, int generator) + { + remainder = (remainder << 1) | bit; + return (remainder & top) == 0 ? remainder : remainder ^ generator; + } + /// The bytes that follow in a page of lanes: zero bits up to 2,036 data /// bits per lane, then the 11 parity bits per lane, then zero bits up to a whole byte. - internal static byte[] Trailer(byte[] data, int lanes) + internal static byte[] Trailer(byte[] data, int lanes) => Trailer(data, lanes, 2047, 11, 9); + + private static byte[] Trailer(byte[] data, int lanes, int codeBits, int parityBits, int tap) { - int degree = 11 * lanes; - BigInteger value = new BigInteger(data, isUnsigned: true) << degree; + int degree = parityBits * lanes; + int omittedZeros = ((1 << parityBits) - 1 - codeBits) * lanes; + BigInteger value = new BigInteger(data, isUnsigned: true) << (degree + omittedZeros); BigInteger mask = (BigInteger.One << degree) - 1; while (value.GetBitLength() > degree) { BigInteger high = value >> degree; - value = (value & mask) ^ high ^ (high << (9 * lanes)); + value = (value & mask) ^ high ^ (high << (tap * lanes)); } - int gap = lanes * 2036 - 8 * data.Length; + int gap = lanes * (codeBits - parityBits) - 8 * data.Length; byte[] bits = (value << gap).ToByteArray(isUnsigned: true); var trailer = new byte[(gap + degree + 7) / 8]; Array.Copy(bits, trailer, Math.Min(bits.Length, trailer.Length)); return trailer; } - /// The stored stream of (last page 16,541 to 64,895 bytes): full pages, then the last page - /// with the smallest odd lane count that holds the content and two bytes of slack. + /// The stored stream of , using bit-polynomial division for every page. internal static byte[] Encode(byte[] content) { var stored = new List(); @@ -41,10 +114,24 @@ internal static byte[] Encode(byte[] content) at += PagedGzipStream.PageDataLength; } byte[] tail = content[at..]; - int lanes = (8 * (tail.Length + 2) + 2035) / 2036; + var (parityBits, tap, reservedBits) = tail.Length switch + { + <= 105 => (4, 3, 4), + <= 256 => (5, 3, 4), + <= 548 => (6, 5, 4), + <= 1_274 => (7, 6, 5), + <= 5_081 => (9, 5, 7), + <= 16_541 => (11, 9, 9), + _ => (11, 9, 16), + }; + int fullCodeBits = (1 << parityBits) - 1; + int dataBits = 8 * tail.Length + reservedBits; + int dataPerFullLane = fullCodeBits - parityBits; + int lanes = Math.Max(65, (dataBits + dataPerFullLane - 1) / dataPerFullLane); if (lanes % 2 == 0) lanes++; + int codeBits = lanes == 65 ? (dataBits + 64) / 65 + parityBits : fullCodeBits; stored.AddRange(tail); - stored.AddRange(Trailer(tail, lanes)); + stored.AddRange(Trailer(tail, lanes, codeBits, parityBits, tap)); return [.. stored]; } } diff --git a/tests/RvtIO.Tests/PageCodecSampleTests.cs b/tests/RvtIO.Tests/PageCodecSampleTests.cs index b334751e..9872920f 100644 --- a/tests/RvtIO.Tests/PageCodecSampleTests.cs +++ b/tests/RvtIO.Tests/PageCodecSampleTests.cs @@ -17,16 +17,18 @@ public class PageCodecSampleTests(ITestOutputHelper output) private sealed record PagedStream(string File, string Name, byte[] Raw); - internal static List ProjectFiles() + internal static List ProjectFiles() => RevitFiles("*.rvt"); + + private static List RevitFiles(params string[] patterns) { var files = new SortedSet(StringComparer.Ordinal); foreach (string root in TestFiles.Roots()) { - foreach (string file in Directory.EnumerateFiles(root, "*.rvt")) files.Add(file); - foreach (string folder in Directory.EnumerateDirectories(root)) - foreach (string file in Directory.EnumerateFiles(folder, "*.rvt")) files.Add(file); + foreach (string folder in Directory.EnumerateDirectories(root).Prepend(root)) + foreach (string pattern in patterns) + files.UnionWith(Directory.EnumerateFiles(folder, pattern)); } - if (files.Count == 0) throw TestFiles.Missing("*.rvt project files"); + if (files.Count == 0) throw TestFiles.Missing(string.Join(", ", patterns) + " Revit files"); return [.. files]; } @@ -59,6 +61,148 @@ private static int MemberEnd(byte[] body) return start + GzipMember.HeaderLength + (int)inflater.TotalIn + 8; } + [SkippableTheory] + [InlineData(105, 4, "PartitionTable")] + [InlineData(106, 5, "DocumentIncrementTable")] + [InlineData(256, 5, "DocumentIncrementTable")] + [InlineData(257, 6, "DocumentIncrementTable")] + [InlineData(549, 7, "DocumentIncrementTable")] + public void NativeShortTailBoundary_UsesTheExpectedParityWidth(int contentBytes, int parityBits, string streamName) + { + string path = TestFiles.Find($"crcio-tail-{contentBytes}.rvt"); + using var root = RootStorage.OpenRead(path); + using var stream = root.OpenStorage("Global").OpenStream(streamName); + Assert.InRange(stream.Length, contentBytes + 1L, PagedGzipStream.PageStride - 1L); + var native = new byte[stream.Length]; + stream.ReadExactly(native); + + byte[]? decoded = PagedGzipStream.Decompress(native); + Assert.NotNull(decoded); + Assert.Equal(contentBytes, MemberEnd(native)); + var layout = Assert.Single(PageCodecReference.ShortTailLayouts(native)); + Assert.Equal(parityBits, layout.ParityBits); + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 0), PageCodec.Verify(native)); + + byte[] encoded = PageCodec.Encode(native.AsSpan(0, contentBytes)); + Assert.Equal(layout, Assert.Single(PageCodecReference.ShortTailLayouts(encoded))); + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 0), PageCodec.Verify(encoded)); + Assert.Equal(decoded, PagedGzipStream.Decompress(encoded)); + + native[layout.DataEnd / 8] ^= (byte)(1 << (layout.DataEnd % 8)); + Assert.Equal(decoded, PagedGzipStream.Decompress(native)); + Assert.Equal(new PageCheck(PageCheckStatus.BadTail, 0), PageCodec.Verify(native)); + } + + [SkippableTheory] + [InlineData(548, 77, 63, 6, 0x61)] + [InlineData(1_274, 85, 127, 7, 0xC1)] + [InlineData(1_275, 65, 167, 9, 0x221)] + [InlineData(5_081, 81, 511, 9, 0x221)] + [InlineData(5_082, 65, 637, 11, 0xA01)] + [InlineData(16_541, 65, 2_047, 11, 0xA01)] + [InlineData(16_542, 67, 2_047, 11, 0xA01)] + public void NativePartitionTailBoundary_MatchesTheExpectedLayout(int contentBytes, int lanes, int codeBits, + int parityBits, int generator) + { + string path = TestFiles.Find($"crcio-tail-{contentBytes}.rvt"); + using var root = RootStorage.OpenRead(path); + var framing = RecordRouting.Begin(FormatsSchema.TryRead(root), out string? failure); + Assert.True(framing is not null, failure); + + bool Frames(byte[] raw) => PartitionFraming.Walk(raw, framing.Tags, framing.IdWidth, _ => { }, out _, out _); + + // The partition must frame through its terminator at exactly this length. + byte[] native = Assert.Single(PagedStreams(path), stream => + stream.Name.StartsWith("Partitions/", StringComparison.Ordinal) && + stream.Raw.Length > contentBytes && stream.Raw.Length < PagedGzipStream.PageDataLength && + Frames(stream.Raw[..contentBytes]) && !Frames(stream.Raw[..(contentBytes - 1)])).Raw; + + var layout = new PageCodecReference.ShortTailLayout(lanes, codeBits, parityBits, generator); + Assert.True(PageCodecReference.MatchesShortTail(native, layout)); + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 0), PageCodec.Verify(native)); + + byte[] content = native[..contentBytes]; + byte[] encoded = PageCodec.Encode(content); + Assert.True(PageCodecReference.MatchesShortTail(encoded, layout)); + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 0), PageCodec.Verify(encoded)); + Assert.Equal(content, encoded[..contentBytes]); + Assert.True(Frames(encoded)); + + native[layout.DataEnd / 8] ^= (byte)(1 << (layout.DataEnd % 8)); + Assert.True(Frames(native)); + Assert.Equal(new PageCheck(PageCheckStatus.BadTail, 0), PageCodec.Verify(native)); + } + + [SkippableFact] + public void NativeShortTails_MatchTheIndependentParityCheck() + { + var counts = new SortedDictionary(); + var rewritten = new HashSet(); + int measuredFiles = 0; + foreach (string path in RevitFiles("*.rvt", "*.rfa", "*.rte", "*.rft")) + { + using var root = RootStorage.OpenRead(path); + var framing = RecordRouting.Begin(FormatsSchema.TryRead(root), out _); + bool measured = false; + foreach (var stream in PagedStreams(path)) + { + byte[] raw = stream.Raw; + int pages = raw.Length / PagedGzipStream.PageStride; + int size = raw.Length % PagedGzipStream.PageStride; + if (size is < PageCodecReference.SmallestMeasuredTailSize or >= PageCodecReference.FirstLongTailSize) continue; + + byte[]? decoded = null; + if (stream.Name.StartsWith("Partitions/", StringComparison.Ordinal)) + { + if (framing == null || !uint.TryParse(stream.Name.AsSpan("Partitions/".Length), out _) || + !PartitionFraming.Walk(raw, framing.Tags, framing.IdWidth, _ => { }, out _, out _)) + continue; + } + else if ((decoded = PagedGzipStream.Decompress(raw)) == null) + continue; + + var tail = raw.AsSpan(raw.Length - size); + var layouts = PageCodecReference.ShortTailLayouts(tail); + Assert.True(layouts.Count == 1, $"{stream.File} {stream.Name}: expected one short-tail layout, got {layouts.Count}."); + var layout = layouts[0]; + measured = true; + counts[layout.ParityBits] = counts.GetValueOrDefault(layout.ParityBits) + 1; + Assert.Equal(new PageCheck(PageCheckStatus.Valid, pages), PageCodec.Verify(raw)); + + if (decoded is not null && + PagedGzipStream.RemoveSegments(raw) is { } body && MemberEnd(body) is > 0 and var end) + { + int tailStart = pages * PagedGzipStream.PageDataLength; + int tailLength = end - tailStart; + Assert.True(tailLength * 8 <= layout.DataEnd); + if (tailLength >= PageCodec.MinTailLength) + { + byte[] encodedTail = PageCodec.Encode(body.AsSpan(tailStart, tailLength)); + Assert.True(PageCodecReference.MatchesShortTail(encodedTail, layout), + $"{stream.File} {stream.Name}: the short writer selected a different layout for {tailLength} content bytes."); + } + + // Also exercise complete-stream rewriting and parity-only damage once per observed code. + if (!rewritten.Add(layout.ParityBits)) continue; + byte[] stored = PageCodec.EncodePadded(body.AsSpan(0, end)); + Assert.Equal(PageCheckStatus.Valid, PageCodec.Verify(stored).Status); + Assert.Equal(decoded, PagedGzipStream.Decompress(stored)); + + // The gzip payload is intact if only a page parity bit changes. + int parityByte = raw.Length - size + layout.DataEnd / 8; + raw[parityByte] ^= (byte)(1 << (layout.DataEnd % 8)); + Assert.Equal(decoded, PagedGzipStream.Decompress(raw)); + Assert.Equal(new PageCheck(PageCheckStatus.BadTail, pages), PageCodec.Verify(raw)); + Assert.Throws(() => PagedStreamCodec.ReadPrefix(raw)); + } + } + if (measured) measuredFiles++; + } + if (measuredFiles == 0) throw new SkipException("No native short pages in a CRC-checked gzip or framed partition stream."); + output.WriteLine($"Revit files={measuredFiles}; short tails by parity width: " + + string.Join(", ", counts.Select(pair => $"{pair.Key} bits={pair.Value}"))); + } + [SkippableFact] public void FullPages_OfRealStreams_AreReproducedByteForByte() { @@ -94,15 +238,15 @@ public void FullPages_OfRealStreams_AreReproducedByteForByte() } int tailStart = fullPages * PagedGzipStream.PageStride; - if (raw.Length == tailStart) continue; + if (raw.Length - tailStart < PageCodecReference.FirstLongTailSize) continue; var tail = PageCodec.Verify(raw.AsSpan(tailStart)); Assert.True(tail.Status is PageCheckStatus.Valid or PageCheckStatus.UnsupportedTail, - $"{stream.File} {stream.Name}: the last page has a length this codec writes, with other check bytes"); + $"{stream.File} {stream.Name}: the long last page has a length this codec writes, with other check bytes"); if (tail.Status == PageCheckStatus.Valid) writtenForm++; else otherForm++; } } output.WriteLine($"files={files} streams={streams} full pages={pages} reproduced from the payload={reproduced} " + - $"accepted with set bits after the payload={markedPages}; last pages in the written form={writtenForm}, in another form (not checked)={otherForm}"); + $"accepted with set bits after the payload={markedPages}; long last pages in the written form={writtenForm}, in another form={otherForm}"); Assert.Equal(pages, reproduced + markedPages); Assert.True(reproduced > 0 && writtenForm > 0); } @@ -117,7 +261,8 @@ public void SingleMemberStreams_WithALastPageOfTheWrittenForm_KeepTheirLengthAnd { byte[] raw = stream.Raw; int tailStart = raw.Length / PagedGzipStream.PageStride * PagedGzipStream.PageStride; - if (raw.Length == tailStart || PageCodec.Verify(raw.AsSpan(tailStart)).Status != PageCheckStatus.Valid) + if (raw.Length - tailStart < PageCodecReference.FirstLongTailSize || + PageCodec.Verify(raw.AsSpan(tailStart)).Status != PageCheckStatus.Valid) { notWritten++; // the last page is stored in a form this codec does not write continue; diff --git a/tests/RvtIO.Tests/PageCodecTests.cs b/tests/RvtIO.Tests/PageCodecTests.cs index 38a58acb..1326dcde 100644 --- a/tests/RvtIO.Tests/PageCodecTests.cs +++ b/tests/RvtIO.Tests/PageCodecTests.cs @@ -133,7 +133,7 @@ public void Trailer_StartsWithTheZeroBitsThatTheReaderChecks() // Last page lengths and what the rule gives for them, worked out by hand: D is the smallest odd number with D * 2036 >= 8 * (length + 2) // and the stored length is ceil(D * 2047 / 8) (for example 67 * 2047 = 137,149 bits = 17,143.6 bytes). [Theory] - [InlineData(16_541, 67, 17_144)] + [InlineData(16_542, 67, 17_144)] [InlineData(17_049, 67, 17_144)] [InlineData(17_050, 69, 17_656)] [InlineData(20_000, 79, 20_215)] @@ -161,10 +161,10 @@ public void LastPage_FollowsTheLaneRule(int length, int lanes, int storedLength) [InlineData(0)] [InlineData(1)] [InlineData(2)] - [InlineData(16_540)] + [InlineData(43)] [InlineData(PageData)] [InlineData(PageData + 1)] - [InlineData(PageData + 16_540)] + [InlineData(PageData + 43)] [InlineData(2 * PageData)] [InlineData(3 * PageData)] public void Encode_RefusesALastPageItDoesNotWrite(int length) @@ -173,15 +173,15 @@ public void Encode_RefusesALastPageItDoesNotWrite(int length) } [Theory] - [InlineData(0, 16_541)] - [InlineData(1, 16_540)] - [InlineData(16_540, 1)] - [InlineData(16_541, 0)] + [InlineData(0, 44)] + [InlineData(1, 43)] + [InlineData(43, 1)] + [InlineData(44, 0)] [InlineData(PageData - 1, 0)] - [InlineData(PageData, 16_541)] - [InlineData(PageData + 1, 16_540)] - [InlineData(PageData + 16_541, 0)] - [InlineData(2 * PageData, 16_541)] + [InlineData(PageData, 44)] + [InlineData(PageData + 1, 43)] + [InlineData(PageData + 44, 0)] + [InlineData(2 * PageData, 44)] [InlineData(3 * PageData - 1, 0)] public void NaturalPadding_GivesTheBytesThatMakeALastPageThatIsWritten(int length, int padding) { @@ -194,7 +194,8 @@ public static IEnumerable Sizes() // The sizes around every boundary of the layout, a few pages, and random ones. var sizes = new SortedSet { - 0, 1, 2, 3, 255, 4_096, 16_539, 16_540, 16_541, 16_542, PageData - 2, PageData - 1, PageData, PageData + 1, + 0, 1, 2, 3, 43, 44, 105, 106, 255, 256, 257, 548, 549, 1_274, 1_275, 4_096, 5_081, 5_082, + 16_539, 16_540, 16_541, 16_542, PageData - 2, PageData - 1, PageData, PageData + 1, PageData + 16_540, PageData + 16_541, 2 * PageData - 1, 2 * PageData, 2 * PageData + 1, 3 * PageData + 17_000, }; var random = new Random(2024); @@ -219,6 +220,34 @@ public void EncodePadded_IsTheReferenceStream_AndTheReaderRemovesExactlyItsSegme Assert.Equal(padded, body[..padded.Length]); } + [Theory] + [InlineData(44, 65, 10, 4, 0x19, 82)] + [InlineData(88, 65, 15, 4, 0x19, 122)] + [InlineData(89, 67, 15, 4, 0x19, 126)] + [InlineData(105, 77, 15, 4, 0x19, 145)] + [InlineData(106, 65, 19, 5, 0x29, 155)] + [InlineData(256, 79, 31, 5, 0x29, 307)] + [InlineData(257, 65, 38, 6, 0x61, 309)] + [InlineData(548, 77, 63, 6, 0x61, 607)] + [InlineData(549, 65, 75, 7, 0xC1, 610)] + [InlineData(1_274, 85, 127, 7, 0xC1, 1_350)] + [InlineData(1_275, 65, 167, 9, 0x221, 1_357)] + [InlineData(5_081, 81, 511, 9, 0x221, 5_174)] + [InlineData(5_082, 65, 637, 11, 0xA01, 5_176)] + [InlineData(16_541, 65, 2_047, 11, 0xA01, 16_632)] + public void Encode_SelectsTheShortLayoutAtItsBoundaries(int length, int lanes, int codeBits, int parityBits, + int generator, int storedLength) + { + byte[] content = Pattern(length); + byte[] stored = PageCodec.Encode(content); + var layout = new PageCodecReference.ShortTailLayout(lanes, codeBits, parityBits, generator); + Assert.Equal(storedLength, stored.Length); + Assert.Equal(content, stored[..length]); + Assert.True(PageCodecReference.MatchesShortTail(stored, layout)); + Assert.Equal(PageCodecReference.Encode(content), stored); + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 0), PageCodec.Verify(stored)); + } + [Fact] public void Verify_ChecksAPageThatEndsTheStreamLikeAnyFullPage() { @@ -274,10 +303,53 @@ public void Verify_DoesNotGuess_ForALastPageOfAnotherLength() byte[] stored = PageCodec.Encode(Random(PageData + 20_000, 41)); Assert.Equal(PageCheckStatus.UnsupportedTail, PageCodec.Verify(stored[..^1]).Status); Assert.Equal(PageCheckStatus.UnsupportedTail, PageCodec.Verify([.. stored, 0]).Status); + Assert.Equal(new PageCheck(PageCheckStatus.UnsupportedTail, 0), PageCodec.Verify(stored[..81])); Assert.Equal(new PageCheck(PageCheckStatus.UnsupportedTail, 0), PageCodec.Verify(stored[..100])); Assert.Equal(new PageCheck(PageCheckStatus.UnsupportedTail, 0), PageCodec.Verify(stored[..(PageStride - 1)])); } + // For a single bit in lane 0, divide y^(p + 2^p - 1 - k) by the generator. + // The remainder bits start at D * (k - p), in lane 0 of each parity plane. + [Theory] + [InlineData(82, 65, 10, 4, 0x19, new[] { 390, 520 })] + [InlineData(130, 69, 15, 4, 0x19, new[] { 759, 966 })] + [InlineData(179, 65, 22, 5, 0x29, new[] { 1105, 1170 })] + [InlineData(268, 69, 31, 5, 0x29, new[] { 1794, 2001 })] + [InlineData(399, 65, 49, 6, 0x61, new[] { 2925, 2990, 3120 })] + [InlineData(607, 77, 63, 6, 0x61, new[] { 4389, 4774 })] + [InlineData(618, 65, 76, 7, 0xC1, new[] { 4485, 4550, 4680, 4810 })] + [InlineData(1_096, 69, 127, 7, 0xC1, new[] { 8280, 8694 })] + [InlineData(1_365, 65, 168, 9, 0x221, new[] { 10400, 10660, 10725, 10790, 10855 })] + [InlineData(4_280, 67, 511, 9, 0x221, new[] { 33634, 33969 })] + [InlineData(5_225, 65, 643, 11, 0xA01, new[] { 41210, 41275, 41340, 41470, 41535 })] + [InlineData(16_502, 65, 2_031, 11, 0xA01, new[] { 131300, 131365, 131430, 131560, 131625, 131690, 131820, 131885 })] + public void Verify_ChecksNativeShortTailParityAndPadding(int size, int lanes, int codeBits, + int parityBits, int generator, int[] parityPositions) + { + var layout = new PageCodecReference.ShortTailLayout(lanes, codeBits, parityBits, generator); + byte[] tail = WithBits(size, [0, .. parityPositions]); + Assert.Contains(layout, PageCodecReference.ShortTailLayouts(tail)); + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 0), PageCodec.Verify(tail)); + + byte[] content = Random(PageData, size); + byte[] stored = [.. content, .. PageCodec.FullPageTrailer(content), .. tail]; + Assert.Equal(new PageCheck(PageCheckStatus.Valid, 1), PageCodec.Verify(stored)); + + foreach (int bit in new[] { 0, layout.DataEnd - 1, layout.DataEnd, layout.ParityEnd - 1, size * 8 - 1 }.Distinct()) + { + byte mask = (byte)(1 << (bit % 8)); + tail[bit / 8] ^= mask; + stored[PageStride + bit / 8] ^= mask; + Assert.False(PageCodecReference.MatchesShortTail(tail, layout)); + Assert.Equal(new PageCheck(PageCheckStatus.BadTail, 0), PageCodec.Verify(tail)); + Assert.Equal(new PageCheck(PageCheckStatus.BadTail, 1), PageCodec.Verify(stored)); + tail[bit / 8] ^= mask; + stored[PageStride + bit / 8] ^= mask; + } + stored[0] ^= 1; + Assert.Equal(new PageCheck(PageCheckStatus.BadPage, 0), PageCodec.Verify(stored)); + } + [Fact] public void Verify_ReportsTheFirstBadPage() { diff --git a/tests/RvtIO.Tests/SharedParameterAuditTests.cs b/tests/RvtIO.Tests/SharedParameterAuditTests.cs new file mode 100644 index 00000000..36810943 --- /dev/null +++ b/tests/RvtIO.Tests/SharedParameterAuditTests.cs @@ -0,0 +1,106 @@ +using System.Text; +using RvtIO.Cli; +using RvtIO.Diagnostics; +using Xunit; + +namespace RvtIO.Tests; + +public sealed class SharedParameterAuditTests +{ + private const string Header = "*PARAM\tGUID\tNAME\tDATATYPE\tDATACATEGORY\tGROUP\tVISIBLE\tDESCRIPTION"; + private static readonly Guid A = new("10000000-0000-0000-0000-000000000001"); + private static readonly Guid B = new("10000000-0000-0000-0000-000000000002"); + private static readonly Guid C = new("10000000-0000-0000-0000-000000000003"); + private static readonly Guid D = new("10000000-0000-0000-0000-000000000004"); + private static readonly Guid E = new("10000000-0000-0000-0000-000000000005"); + + [Fact] + public void PairsByGuidAndRetainsTheRowsBehindEachCollision() + { + var report = SharedParameterAudit.Compare(new([ + Model(10, A, "Original", "LENGTH", description: "Stored"), Model(20, B, "Shared Name", "TEXT"), + Model(30, C, "Duplicate", "TEXT"), Model(31, C, "Duplicate", "TEXT"), + Model(40, E, "Family", "FAMILYTYPE", category: -2000011), + ], []), Parse( + Row(A, "New name", "AREA", description: ""), Row(C, "Duplicate"), Row(C, "Duplicate", "INTEGER"), + Row(D, "shared name"), Row(E, "Family", "FAMILYTYPE", "-2000014"))); + + Assert.Equal(new[] { "name-mismatch", "description-mismatch", "incompatible-type" }, report.Parameters[0].Findings); + Assert.Equal("model-only", Assert.Single(report.Parameters[1].Findings)); + Assert.Equal(new[] { "duplicate-model-guid", "duplicate-fop-guid" }, report.Parameters[2].Findings); + Assert.Equal(new long[] { 30, 31 }, report.Parameters[2].Model.Select(item => item.ElementId)); + Assert.Equal(new[] { 3, 4 }, report.Parameters[2].Fop.Select(item => item.Line)); + Assert.Equal("fop-only", Assert.Single(report.Parameters[3].Findings)); + Assert.Equal("incompatible-type", Assert.Single(report.Parameters[4].Findings)); + var collision = Assert.Single(report.NameCollisions); + Assert.Equal("Shared Name", collision.Name); + Assert.Equal(new[] { B, D }, collision.Guids); + } + + [Fact] + public void MarksUnknownFieldsAndDoesNotAssertAbsenceFromAPartialInventory() + { + var report = SharedParameterAudit.Compare(new([ + Model(10, A, "Unknown", null), Model(20, B, "Family", "FAMILYTYPE"), + Model(30, C, "Verified", "TEXT", description: ""), + ], [new(90, "unreadable-definition")]), Parse( + Row(A, "Unknown", "TEXT", description: ""), Row(B, "Family", "FAMILYTYPE", "-2000014"), + Row(C, "Verified", "text", description: ""), Row(D, "Unknown model GUID"))); + + Assert.Equal(new[] { "description-unverified", "type-unverified" }, report.Parameters[0].Findings); + Assert.Equal("type-unverified", Assert.Single(report.Parameters[1].Findings)); + Assert.Empty(report.Parameters[2].Findings); + Assert.Equal("not-confirmed-in-model", Assert.Single(report.Parameters[3].Findings)); + Assert.Equal(90, Assert.Single(report.UnreadableDefinitions).ElementId); + } + + [Theory] + [InlineData("PARAM\tbroken\tName\tTEXT\t\t1\t1", "GUID")] + [InlineData("PARAM\t10000000-0000-0000-0000-000000000001\tName\tFAMILYTYPE\t\t1\t1", "DATACATEGORY")] + [InlineData("PARAM 10000000-0000-0000-0000-000000000001 bad columns", "tab-delimited")] + public void RejectsInvalidRowsBeforeWritingAReport(string row, string message) + { + string fop = TestFiles.Scratch(Guid.NewGuid() + ".txt"); + string report = fop + ".json"; + File.WriteAllText(fop, Header + "\n" + row, Encoding.Unicode); + try + { + using var error = new StringWriter(); + int result = SharedParameterAuditCommand.Run([fop + ".rvt", fop, "--report", report], TextWriter.Null, error); + Assert.Equal(RvtExitCodes.InputError, result); + Assert.Contains("line 2", error.ToString()); + Assert.Contains(message, error.ToString()); + Assert.False(File.Exists(report)); + } + finally + { + File.Delete(fop); + } + } + + [Fact] + public void RejectsAnOutputPathThatNamesEitherInput() + { + string model = TestFiles.Scratch("audit-source.rvt"); + string fop = TestFiles.Scratch("audit-source.txt"); + foreach (string input in new[] { model, fop }) + { + using var error = new StringWriter(); + Assert.Equal(RvtExitCodes.Usage, + SharedParameterAuditCommand.Run([model, fop, "--report", input], TextWriter.Null, error)); + Assert.Contains("distinct from both inputs", error.ToString()); + } + } + + private static List Parse(params string[] rows) => + SharedParameterAudit.ParseFop(new StringReader(Header + "\n" + string.Join('\n', rows))); + + private static string Row(Guid guid, string name, string type = "TEXT", string category = "", string? description = null) + { + string row = $"PARAM\t{guid}\t{name}\t{type}\t{category}\t1\t1"; + return description == null ? row : row + "\t" + description; + } + + private static SharedParameterInventory.Definition Model(long id, Guid guid, string name, string? type, long? category = null, + string? description = null) => new(id, guid, name, description, type, category, "TestDefinition", null); +} diff --git a/tests/RvtIO.Tests/StreamInputTests.cs b/tests/RvtIO.Tests/StreamInputTests.cs index 17929b45..03c23310 100644 --- a/tests/RvtIO.Tests/StreamInputTests.cs +++ b/tests/RvtIO.Tests/StreamInputTests.cs @@ -19,6 +19,10 @@ private static byte[] SyntheticRvt() try { CliExitCodeTests.WriteSyntheticRvt(path, [1, 2, 3]); + // Keep the fixed read limits inside the container even when the page trailers are short. + using (var root = OpenMcdf.RootStorage.Open(path, FileMode.Open)) + using (var padding = root.CreateStream("ReadBudget")) + padding.Write(new byte[64 * 1024]); return File.ReadAllBytes(path); } finally { File.Delete(path); }