From 08eee3d000f3b1888dcfd4fb4f386ed1daaa1ee3 Mon Sep 17 00:00:00 2001 From: antoineatsoprasteria Date: Thu, 3 Dec 2026 14:05:38 +0100 Subject: [PATCH 1/3] Fix #469: Moved to V7 guid --- README.md | 3 +- .../OpenApiSchemaExtensionsTestFixture.cs | 7 ++ .../Extensions/OpenApiSchemaExtensions.cs | 13 ++++ .../OpenApiDtoGenerator.cs | 5 ++ .../IdentifierTestFixture.cs | 77 +++++++++++++++++++ .../SysML2.NET.Identifiers.Tests.csproj | 32 ++++++++ SysML2.NET.Identifiers/Identifier.cs | 52 +++++++++++++ .../SysML2.NET.Identifiers.csproj | 31 ++++++++ .../Implied/ImpliedRelationshipFactory.cs | 18 ++--- .../IdentifierExtensionsTestFixture.cs | 56 ++++++++++++++ ...tionallyIdentifiedExtensionsTestFixture.cs | 49 ++++++++++++ SysML2.NET.sln | 28 +++++++ SysML2.NET/Extensions/IdentifierExtensions.cs | 75 ++++++++++++++++++ .../OptionallyIdentifiedExtensions.cs | 47 +++++++++++ .../PSM/AutoGenDto/ExternalDataRequest.cs | 2 +- .../AutoGenDto/ExternalRelationshipRequest.cs | 2 +- .../PSM/AutoGenDto/ProjectUsageRequest.cs | 2 +- SysML2.NET/PSM/DTO/IOptionallyIdentified.cs | 24 ++++++ .../PSM/DTO/Mapping/CommitRequest.Mapping.cs | 6 +- SysML2.NET/SysML2.NET.csproj | 4 + 20 files changed, 516 insertions(+), 17 deletions(-) create mode 100644 SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs create mode 100644 SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj create mode 100644 SysML2.NET.Identifiers/Identifier.cs create mode 100644 SysML2.NET.Identifiers/SysML2.NET.Identifiers.csproj create mode 100644 SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs create mode 100644 SysML2.NET.Tests/Extensions/OptionallyIdentifiedExtensionsTestFixture.cs create mode 100644 SysML2.NET/Extensions/IdentifierExtensions.cs create mode 100644 SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs create mode 100644 SysML2.NET/PSM/DTO/IOptionallyIdentified.cs diff --git a/README.md b/README.md index 3d97d4fb3..e38ddc4bc 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ project ----------------------------------------------------------------------------------------------------- | ------------ [SysML2.NET](https://www.nuget.org/packages/SysML2.NET) | ![NuGet Version](https://img.shields.io/nuget/v/SysML2.NET) [SysML2.NET.Extensions](https://www.nuget.org/packages/SysML2.NET.Extensions) | ![NuGet Version](https://img.shields.io/nuget/v/SysML2.NET.Extensions) +[SysML2.NET.Identifiers](https://www.nuget.org/packages/SysML2.NET.Identifiers) | ![NuGet Version](https://img.shields.io/nuget/v/SysML2.NET.Identifiers) [SysML2.NET.Semantics](https://www.nuget.org/packages/SysML2.NET.Semantics) | ![NuGet Version](https://img.shields.io/nuget/v/SysML2.NET.Semantics) [SysML2.NET.Serializer.Json](https://www.nuget.org/packages/SysML2.NET.Serializer.Json) | ![NuGet Version](https://img.shields.io/nuget/v/SysML2.NET.Serializer.Json) [SysML2.NET.Serializer.Xmi](https://www.nuget.org/packages/SysML2.NET.Serializer.Xmi) | ![NuGet Version](https://img.shields.io/nuget/v/SysML2.NET.Serializer.Xmi) @@ -54,7 +55,7 @@ Every NuGet version is declared once, in [Directory.Packages.props](Directory.Pa The redistributable libraries multi-target `netstandard2.1;net10.0`, so a referenced version is a **minimum floor** for every downstream consumer. The version policy follows from that: -- **Libraries** (`SysML2.NET`, `SysML2.NET.Serializer.*`, `SysML2.NET.Dal`, `SysML2.NET.REST`, `SysML2.NET.Kpar`, `SysML2.NET.Extensions`, `SysML2.NET.Semantics`, `SysML2.NET.Validation`) reference the lowest version that provides the APIs used. Stable framework abstractions stay at an LTS floor; serialization and cryptography packages track current. +- **Libraries** (`SysML2.NET`, `SysML2.NET.Serializer.*`, `SysML2.NET.Dal`, `SysML2.NET.REST`, `SysML2.NET.Kpar`, `SysML2.NET.Extensions`, `SysML2.NET.Identifiers`, `SysML2.NET.Semantics`, `SysML2.NET.Validation`) reference the lowest version that provides the APIs used. Stable framework abstractions stay at an LTS floor; serialization and cryptography packages track current. - **Applications and test projects** track current versions. - A library dependency is raised only when a required new API needs it, or when a CVE affects that package. diff --git a/SysML2.NET.CodeGenerator.Tests/Extensions/OpenApiSchemaExtensionsTestFixture.cs b/SysML2.NET.CodeGenerator.Tests/Extensions/OpenApiSchemaExtensionsTestFixture.cs index 7f430ab04..19ab7202d 100644 --- a/SysML2.NET.CodeGenerator.Tests/Extensions/OpenApiSchemaExtensionsTestFixture.cs +++ b/SysML2.NET.CodeGenerator.Tests/Extensions/OpenApiSchemaExtensionsTestFixture.cs @@ -40,6 +40,7 @@ public void VerifySchemaStructureQueries() Assert.That(() => ((IOpenApiSchema)null).QueryUnionAlternativeNames(), Throws.TypeOf()); Assert.That(() => ((IOpenApiSchema)null).QueryTypeDiscriminator(), Throws.TypeOf()); Assert.That(() => ((IOpenApiSchema)null).QueryHasRequiredIdentifier(), Throws.TypeOf()); + Assert.That(() => ((IOpenApiSchema)null).QueryHasOptionalIdentifier(), Throws.TypeOf()); Assert.That(() => ((IOpenApiSchema)null).QueryMappableProperties("Project"), Throws.TypeOf()); Assert.That(() => this.schemas["Project"].QueryMappableProperties(null), Throws.TypeOf()); @@ -62,6 +63,12 @@ public void VerifySchemaStructureQueries() Assert.That(this.schemas["PrimitiveConstraint"].QueryHasRequiredIdentifier(), Is.False); Assert.That(this.schemas["ProjectUsageRequest"].QueryHasRequiredIdentifier(), Is.False); + Assert.That(this.schemas["ProjectUsageRequest"].QueryHasOptionalIdentifier(), Is.True); + Assert.That(this.schemas["ExternalDataRequest"].QueryHasOptionalIdentifier(), Is.True); + Assert.That(this.schemas["Project"].QueryHasOptionalIdentifier(), Is.False); + Assert.That(this.schemas["DataIdentityRequest"].QueryHasOptionalIdentifier(), Is.False); + Assert.That(this.schemas["Error"].QueryHasOptionalIdentifier(), Is.False); + Assert.That(this.schemas["Project"].QueryTypeDiscriminator(), Is.EqualTo("Project")); Assert.That(this.schemas["ProjectRequest"].QueryTypeDiscriminator(), Is.EqualTo("Project")); Assert.That(this.schemas["Data"].QueryTypeDiscriminator(), Is.Null); diff --git a/SysML2.NET.CodeGenerator/Extensions/OpenApiSchemaExtensions.cs b/SysML2.NET.CodeGenerator/Extensions/OpenApiSchemaExtensions.cs index 65cfc80e8..52d2c8c48 100644 --- a/SysML2.NET.CodeGenerator/Extensions/OpenApiSchemaExtensions.cs +++ b/SysML2.NET.CodeGenerator/Extensions/OpenApiSchemaExtensions.cs @@ -156,6 +156,19 @@ public static bool QueryHasRequiredIdentifier(this IOpenApiSchema schema) && schema.Required?.Contains(IdentifierPropertyName) == true; } + /// + /// Queries whether the schema declares an identifier that it does not list as required + /// + /// The subject . + /// True when the identifier is declared and optional. + public static bool QueryHasOptionalIdentifier(this IOpenApiSchema schema) + { + ArgumentNullException.ThrowIfNull(schema); + + return schema.Properties?.ContainsKey(IdentifierPropertyName) == true + && schema.Required?.Contains(IdentifierPropertyName) != true; + } + /// /// Queries the properties of the schema that can be expressed as C# properties /// diff --git a/SysML2.NET.CodeGenerator/Generators/OpenApiHandleBarsGenerators/OpenApiDtoGenerator.cs b/SysML2.NET.CodeGenerator/Generators/OpenApiHandleBarsGenerators/OpenApiDtoGenerator.cs index 6c788c4bd..6542340d8 100644 --- a/SysML2.NET.CodeGenerator/Generators/OpenApiHandleBarsGenerators/OpenApiDtoGenerator.cs +++ b/SysML2.NET.CodeGenerator/Generators/OpenApiHandleBarsGenerators/OpenApiDtoGenerator.cs @@ -253,6 +253,11 @@ private static IEnumerable QueryFamilyInterfaces(string schemaName, IOpe { yield return "SysML2.NET.Common.IIdentified"; } + + if (schema.QueryHasOptionalIdentifier()) + { + yield return "IOptionallyIdentified"; + } } /// diff --git a/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs b/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs new file mode 100644 index 000000000..641399a28 --- /dev/null +++ b/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs @@ -0,0 +1,77 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Identifiers.Tests +{ + using System; + using System.Globalization; + using System.Linq; + + using NUnit.Framework; + + [TestFixture] + public class IdentifierTestFixture + { + private const string VariantDigits = "89ab"; + + [Test] + public void VerifyNewId() + { + var before = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var identifier = Identifier.NewId(); + var after = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + var text = identifier.ToString(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(text[14], Is.EqualTo('7')); + Assert.That(VariantDigits, Does.Contain(text[19])); + Assert.That(TimestampOf(identifier), Is.InRange(before, after)); + Assert.That(Identifier.NewId(), Is.Not.EqualTo(identifier)); + } + } + + [Test] + public void VerifyCreateVersion7() + { + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(0x0123_4567_89AB); + var identifier = Identifier.CreateVersion7(timestamp); + var text = identifier.ToString(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(text, Does.StartWith("01234567-89ab-7")); + Assert.That(VariantDigits, Does.Contain(text[19])); + Assert.That(Identifier.CreateVersion7(timestamp), Is.Not.EqualTo(identifier)); + } + + var latest = Identifier.CreateVersion7(DateTimeOffset.MaxValue); + + Assert.That(latest.ToString(), Does.StartWith("e677d21f-dbff-7")); + + var later = Identifier.CreateVersion7(timestamp.AddMilliseconds(1)); + var earlier = Identifier.CreateVersion7(timestamp.AddMilliseconds(-1)); + + Guid[] inCreationOrder = [earlier, identifier, later, latest]; + Guid[] shuffled = [latest, identifier, earlier, later]; + + using (Assert.EnterMultipleScope()) + { + Assert.That(shuffled.Order(), Is.EqualTo(inCreationOrder)); + Assert.That(shuffled.Select(guid => guid.ToString()).Order(StringComparer.Ordinal), Is.EqualTo(inCreationOrder.Select(guid => guid.ToString()))); + } + } + + private static long TimestampOf(Guid identifier) + { + return long.Parse(identifier.ToString("N")[..12], NumberStyles.HexNumber, CultureInfo.InvariantCulture); + } + } +} diff --git a/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj b/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj new file mode 100644 index 000000000..5e973c61b --- /dev/null +++ b/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj @@ -0,0 +1,32 @@ + + + + net10.0 + 14.0 + Starion Group S.A. + Sam Gerene + Nunit test suite for the SysML2.NET.Identifiers library + Copyright © Starion Group S.A. + Apache-2.0 + https://github.com/STARIONGROUP/SysML2.NET.git + Git + false + disable + false + en-US + + + + + + + + + + + + + + + + diff --git a/SysML2.NET.Identifiers/Identifier.cs b/SysML2.NET.Identifiers/Identifier.cs new file mode 100644 index 000000000..ef5bca6ba --- /dev/null +++ b/SysML2.NET.Identifiers/Identifier.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Identifiers +{ + using System; + using System.Security.Cryptography; + + /// + /// Mints the time-ordered identifiers given to new data + /// + public static class Identifier + { + /// + /// Creates a new version 7 UUID, whose leading 48 bits are the current Unix time in milliseconds + /// + /// A new, time-ordered . + public static Guid NewId() + { +#if NET9_0_OR_GREATER + return Guid.CreateVersion7(); +#else + return CreateVersion7(DateTimeOffset.UtcNow); +#endif + } + + /// + /// Creates a version 7 UUID for the supplied timestamp, as laid out by RFC 9562 §5.7 + /// + /// The instant whose Unix time in milliseconds leads the identifier. + /// A carrying the timestamp, 74 random bits, the version 7 and the variant 10. + internal static Guid CreateVersion7(DateTimeOffset timestamp) + { + var milliseconds = timestamp.ToUnixTimeMilliseconds(); + + var random = new byte[10]; + RandomNumberGenerator.Fill(random); + + var versionAndRandomA = (short)(0x7000 | (((random[0] << 8) | random[1]) & 0x0FFF)); + random[2] = (byte)(0x80 | (random[2] & 0x3F)); + + // The (int, short, short, byte[]) constructor keeps the timestamp leading the textual and big-endian forms. + return new Guid((int)(milliseconds >> 16), (short)(milliseconds & 0xFFFF), versionAndRandomA, random[2..]); + } + } +} diff --git a/SysML2.NET.Identifiers/SysML2.NET.Identifiers.csproj b/SysML2.NET.Identifiers/SysML2.NET.Identifiers.csproj new file mode 100644 index 000000000..8a1ad238b --- /dev/null +++ b/SysML2.NET.Identifiers/SysML2.NET.Identifiers.csproj @@ -0,0 +1,31 @@ + + + + + + netstandard2.1;net10.0 + 14.0 + 0.27.1 + Mints the time-ordered UUID version 7 identifiers given to new SysML v2 data, without dependencies. + SysML2.NET.Identifiers + Starion Group S.A. + Copyright © Starion Group S.A. + Apache-2.0 + https://github.com/STARIONGROUP/SysML2.NET.git + Git + Sam Gerené + true + disable + true + true + + + + + + + + + + + diff --git a/SysML2.NET.Semantics/Implied/ImpliedRelationshipFactory.cs b/SysML2.NET.Semantics/Implied/ImpliedRelationshipFactory.cs index b2b5eac00..8e971dfb5 100644 --- a/SysML2.NET.Semantics/Implied/ImpliedRelationshipFactory.cs +++ b/SysML2.NET.Semantics/Implied/ImpliedRelationshipFactory.cs @@ -47,11 +47,10 @@ public ISubclassification CreateImpliedSubclassification(IClassifier specific, I return new Subclassification { - Id = Guid.NewGuid(), IsImplied = true, Subclassifier = specific, Superclassifier = general - }; + }.AssignNewId(); } /// @@ -75,11 +74,10 @@ public ISubsetting CreateImpliedSubsetting(IFeature specific, IFeature general) return new Subsetting { - Id = Guid.NewGuid(), IsImplied = true, SubsettingFeature = specific, SubsettedFeature = general - }; + }.AssignNewId(); } /// @@ -101,12 +99,12 @@ public IFeature CreateImpliedFeatureChain(IFeature first, IFeature second) throw new ArgumentNullException(nameof(second)); } - var chain = new Feature { Id = Guid.NewGuid() }; + var chain = new Feature().AssignNewId(); // The chain is expressed through owned FeatureChainings, which is what chainingFeature derives // from — setting the derived list directly would not survive a re-read of the property. - chain.AssignOwnership(new FeatureChaining { Id = Guid.NewGuid(), IsImplied = true, ChainingFeature = first }); - chain.AssignOwnership(new FeatureChaining { Id = Guid.NewGuid(), IsImplied = true, ChainingFeature = second }); + chain.AssignOwnership(new FeatureChaining { IsImplied = true, ChainingFeature = first }.AssignNewId()); + chain.AssignOwnership(new FeatureChaining { IsImplied = true, ChainingFeature = second }.AssignNewId()); return chain; } @@ -132,11 +130,10 @@ public IRedefinition CreateImpliedRedefinition(IFeature specific, IFeature gener return new Redefinition { - Id = Guid.NewGuid(), IsImplied = true, RedefiningFeature = specific, RedefinedFeature = general - }; + }.AssignNewId(); } /// @@ -160,11 +157,10 @@ public IFeatureTyping CreateImpliedFeatureTyping(IFeature typedFeature, IType ty return new FeatureTyping { - Id = Guid.NewGuid(), IsImplied = true, TypedFeature = typedFeature, Type = type - }; + }.AssignNewId(); } } } diff --git a/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs b/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs new file mode 100644 index 000000000..9c234c1a4 --- /dev/null +++ b/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Tests.Extensions +{ + using System; + + using NUnit.Framework; + + using SysML2.NET.Extensions; + using SysML2.NET.PSM.DTO; + + using DtoPartUsage = SysML2.NET.Core.DTO.Systems.Parts.PartUsage; + using PimCommit = SysML2.NET.PIM.DTO.Commit; + using PocoPartUsage = SysML2.NET.Core.POCO.Systems.Parts.PartUsage; + + [TestFixture] + public class IdentifierExtensionsTestFixture + { + [Test] + public void VerifyAssignNewId() + { + Assert.That(() => ((PimCommit)null).AssignNewId(), Throws.TypeOf()); + + var commit = new PimCommit(); + var project = new Project(); + var pocoPart = new PocoPartUsage(); + var dtoPart = new DtoPartUsage(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(commit.AssignNewId(), Is.SameAs(commit)); + Assert.That(commit.Id.ToString()[14], Is.EqualTo('7')); + Assert.That(project.AssignNewId().Id, Is.Not.EqualTo(Guid.Empty)); + Assert.That(pocoPart.AssignNewId().ElementId, Is.EqualTo(pocoPart.Id.ToString())); + Assert.That(dtoPart.AssignNewId().ElementId, Is.EqualTo(dtoPart.Id.ToString())); + Assert.That(pocoPart.Id, Is.Not.EqualTo(dtoPart.Id)); + } + + var identifier = commit.Id; + + using (Assert.EnterMultipleScope()) + { + Assert.That(commit.AssignNewId, Throws.TypeOf()); + Assert.That(commit.Id, Is.EqualTo(identifier)); + Assert.That(new PocoPartUsage { Id = identifier }.AssignNewId, Throws.TypeOf()); + } + } + } +} diff --git a/SysML2.NET.Tests/Extensions/OptionallyIdentifiedExtensionsTestFixture.cs b/SysML2.NET.Tests/Extensions/OptionallyIdentifiedExtensionsTestFixture.cs new file mode 100644 index 000000000..e19f16e6f --- /dev/null +++ b/SysML2.NET.Tests/Extensions/OptionallyIdentifiedExtensionsTestFixture.cs @@ -0,0 +1,49 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Tests.Extensions +{ + using System; + + using NUnit.Framework; + + using SysML2.NET.Extensions; + using SysML2.NET.PSM.DTO; + + [TestFixture] + public class OptionallyIdentifiedExtensionsTestFixture + { + [Test] + public void VerifyAssignNewId() + { + Assert.That(() => ((ExternalDataRequest)null).AssignNewId(), Throws.TypeOf()); + + var externalData = new ExternalDataRequest(); + var externalRelationship = new ExternalRelationshipRequest { Id = Guid.Empty }; + var projectUsage = new ProjectUsageRequest(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(externalData.AssignNewId(), Is.SameAs(externalData)); + Assert.That(externalData.Id.ToString()[14], Is.EqualTo('7')); + Assert.That(externalRelationship.AssignNewId().Id, Is.Not.EqualTo(Guid.Empty)); + Assert.That(projectUsage.AssignNewId().Id, Is.Not.Null.And.Not.EqualTo(externalData.Id)); + } + + var identifier = externalData.Id; + + using (Assert.EnterMultipleScope()) + { + Assert.That(externalData.AssignNewId, Throws.TypeOf()); + Assert.That(externalData.Id, Is.EqualTo(identifier)); + Assert.That(new ProjectUsageRequest { Id = identifier }.AssignNewId, Throws.TypeOf()); + } + } + } +} diff --git a/SysML2.NET.sln b/SysML2.NET.sln index aa93c9ce6..41ea31be3 100644 --- a/SysML2.NET.sln +++ b/SysML2.NET.sln @@ -80,6 +80,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SysML2.NET.Validation", "Sy EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SysML2.NET.Validation.Tests", "SysML2.NET.Validation.Tests\SysML2.NET.Validation.Tests.csproj", "{42F385BC-BA62-4EEA-9F44-B7CC6F3B9A6F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SysML2.NET.Identifiers", "SysML2.NET.Identifiers\SysML2.NET.Identifiers.csproj", "{287B9D85-BE58-45E9-ACCC-167E167B0F1B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SysML2.NET.Identifiers.Tests", "SysML2.NET.Identifiers.Tests\SysML2.NET.Identifiers.Tests.csproj", "{D4E4904B-EF81-4615-B151-00DEFF5D59BB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -378,6 +382,30 @@ Global {42F385BC-BA62-4EEA-9F44-B7CC6F3B9A6F}.Release|x64.Build.0 = Release|Any CPU {42F385BC-BA62-4EEA-9F44-B7CC6F3B9A6F}.Release|x86.ActiveCfg = Release|Any CPU {42F385BC-BA62-4EEA-9F44-B7CC6F3B9A6F}.Release|x86.Build.0 = Release|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Debug|x64.ActiveCfg = Debug|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Debug|x64.Build.0 = Debug|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Debug|x86.ActiveCfg = Debug|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Debug|x86.Build.0 = Debug|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Release|Any CPU.Build.0 = Release|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Release|x64.ActiveCfg = Release|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Release|x64.Build.0 = Release|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Release|x86.ActiveCfg = Release|Any CPU + {287B9D85-BE58-45E9-ACCC-167E167B0F1B}.Release|x86.Build.0 = Release|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Debug|x64.ActiveCfg = Debug|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Debug|x64.Build.0 = Debug|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Debug|x86.ActiveCfg = Debug|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Debug|x86.Build.0 = Debug|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Release|Any CPU.Build.0 = Release|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Release|x64.ActiveCfg = Release|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Release|x64.Build.0 = Release|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Release|x86.ActiveCfg = Release|Any CPU + {D4E4904B-EF81-4615-B151-00DEFF5D59BB}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/SysML2.NET/Extensions/IdentifierExtensions.cs b/SysML2.NET/Extensions/IdentifierExtensions.cs new file mode 100644 index 000000000..1ade45b88 --- /dev/null +++ b/SysML2.NET/Extensions/IdentifierExtensions.cs @@ -0,0 +1,75 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Extensions +{ + using System; + + using SysML2.NET.Common; + using SysML2.NET.Identifiers; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + + /// + /// Extension methods that give new data its version 7 identifier + /// + public static class IdentifierExtensions + { + /// + /// Identifier assignment for anything identified by a + /// + /// The new data to identify + /// The type of the identified data + extension(T subject) where T : class, IIdentified + { + /// + /// Sets the of the subject, and the ElementId of an element, to a new + /// + /// The subject. + /// If the subject is null + /// If the subject already has an identifier + public T AssignNewId() + { + if (subject == null) + { + throw new ArgumentNullException(nameof(subject)); + } + + var identifier = NewIdForUnidentified(subject.Id); + + switch (subject) + { + case DtoElement element: + element.ElementId = identifier.ToString(); + break; + case PocoElement element: + element.ElementId = identifier.ToString(); + break; + } + + subject.Id = identifier; + return subject; + } + } + + /// + /// Mints a new identifier for data that has none yet + /// + /// The identifier the data carries, null or when it has none. + /// A new version 7 . + /// If is already an identifier + internal static Guid NewIdForUnidentified(Guid? current) + { + return current.GetValueOrDefault() == Guid.Empty + ? Identifier.NewId() + : throw new InvalidOperationException($"The data is already identified by {current}; an identifier never changes."); + } + } +} diff --git a/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs b/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs new file mode 100644 index 000000000..bf350a7ae --- /dev/null +++ b/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs @@ -0,0 +1,47 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Extensions +{ + using System; + + using SysML2.NET.Identifiers; + using SysML2.NET.PSM.DTO; + + /// + /// Extension methods that give a new request its version 7 identifier + /// + public static class OptionallyIdentifiedExtensions + { + /// + /// Identifier assignment for a request whose identifier is optional + /// + /// The request whose new data to identify + /// The type of the request + extension(T request) where T : class, IOptionallyIdentified + { + /// + /// Sets the of the request to a new + /// + /// The request. + /// If the request is null + /// If the request already has an identifier + public T AssignNewId() + { + if (request == null) + { + throw new ArgumentNullException(nameof(request)); + } + + request.Id = IdentifierExtensions.NewIdForUnidentified(request.Id); + return request; + } + } + } +} diff --git a/SysML2.NET/PSM/AutoGenDto/ExternalDataRequest.cs b/SysML2.NET/PSM/AutoGenDto/ExternalDataRequest.cs index f829d29ff..479963560 100644 --- a/SysML2.NET/PSM/AutoGenDto/ExternalDataRequest.cs +++ b/SysML2.NET/PSM/AutoGenDto/ExternalDataRequest.cs @@ -24,7 +24,7 @@ namespace SysML2.NET.PSM.DTO /// Data transfer object that represents the ExternalDataRequest schema of the Systems Modeling API and Services /// [GeneratedCode("SysML2.NET", "latest")] - public partial class ExternalDataRequest : IRequest, SysML2.NET.Common.IDataRequest + public partial class ExternalDataRequest : IOptionallyIdentified, IRequest, SysML2.NET.Common.IDataRequest { /// /// The value of the type discriminator of the ExternalDataRequest schema diff --git a/SysML2.NET/PSM/AutoGenDto/ExternalRelationshipRequest.cs b/SysML2.NET/PSM/AutoGenDto/ExternalRelationshipRequest.cs index 58c884f00..5d45485be 100644 --- a/SysML2.NET/PSM/AutoGenDto/ExternalRelationshipRequest.cs +++ b/SysML2.NET/PSM/AutoGenDto/ExternalRelationshipRequest.cs @@ -24,7 +24,7 @@ namespace SysML2.NET.PSM.DTO /// Data transfer object that represents the ExternalRelationshipRequest schema of the Systems Modeling API and Services /// [GeneratedCode("SysML2.NET", "latest")] - public partial class ExternalRelationshipRequest : IRequest, SysML2.NET.Common.IDataRequest + public partial class ExternalRelationshipRequest : IOptionallyIdentified, IRequest, SysML2.NET.Common.IDataRequest { /// /// The value of the type discriminator of the ExternalRelationshipRequest schema diff --git a/SysML2.NET/PSM/AutoGenDto/ProjectUsageRequest.cs b/SysML2.NET/PSM/AutoGenDto/ProjectUsageRequest.cs index b0df39f1c..884f943f7 100644 --- a/SysML2.NET/PSM/AutoGenDto/ProjectUsageRequest.cs +++ b/SysML2.NET/PSM/AutoGenDto/ProjectUsageRequest.cs @@ -24,7 +24,7 @@ namespace SysML2.NET.PSM.DTO /// Data transfer object that represents the ProjectUsageRequest schema of the Systems Modeling API and Services /// [GeneratedCode("SysML2.NET", "latest")] - public partial class ProjectUsageRequest : IRequest, SysML2.NET.Common.IDataRequest + public partial class ProjectUsageRequest : IOptionallyIdentified, IRequest, SysML2.NET.Common.IDataRequest { /// /// The value of the type discriminator of the ProjectUsageRequest schema diff --git a/SysML2.NET/PSM/DTO/IOptionallyIdentified.cs b/SysML2.NET/PSM/DTO/IOptionallyIdentified.cs new file mode 100644 index 000000000..cddef45c7 --- /dev/null +++ b/SysML2.NET/PSM/DTO/IOptionallyIdentified.cs @@ -0,0 +1,24 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.PSM.DTO +{ + using System; + + /// + /// Implemented by the data transfer objects whose schema declares an identifier without requiring it + /// + public interface IOptionallyIdentified + { + /// + /// Gets or sets the unique identifier, null when the payload carries none + /// + Guid? Id { get; set; } + } +} diff --git a/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs b/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs index 6320245f6..84615c94c 100644 --- a/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs +++ b/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs @@ -13,6 +13,8 @@ namespace SysML2.NET.PSM.DTO using System.Collections.Generic; using System.Linq; + using SysML2.NET.Identifiers; + /// /// Declares the Platform Independent Model counterpart of the Commit request model /// @@ -41,7 +43,7 @@ public PIM.DTO.Commit ToPim() { var commit = new PIM.DTO.Commit { - Id = Guid.NewGuid(), + Id = Identifier.NewId(), Alias = [.. this.Alias ?? []], Description = this.Description, Name = this.Name @@ -50,7 +52,7 @@ public PIM.DTO.Commit ToPim() var change = (this.Change ?? []).Select(request => { var version = request.ToPim(); - version.Id = Guid.NewGuid(); + version.Id = Identifier.NewId(); version.Commit = commit.Id; return version; }).ToList(); diff --git a/SysML2.NET/SysML2.NET.csproj b/SysML2.NET/SysML2.NET.csproj index adf9a3dac..a094c8bd8 100644 --- a/SysML2.NET/SysML2.NET.csproj +++ b/SysML2.NET/SysML2.NET.csproj @@ -28,6 +28,10 @@ + + + + From 82131ac093567260b6371bc97a63079f57ff2bb3 Mon Sep 17 00:00:00 2001 From: antoineatsoprasteria Date: Thu, 3 Dec 2026 14:18:30 +0100 Subject: [PATCH 2/3] test covers netstandard 2.1 --- SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs | 10 ++++++++++ .../SysML2.NET.Identifiers.Tests.csproj | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs b/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs index 641399a28..8dab0d4fe 100644 --- a/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs +++ b/SysML2.NET.Identifiers.Tests/IdentifierTestFixture.cs @@ -12,6 +12,8 @@ namespace SysML2.NET.Identifiers.Tests using System; using System.Globalization; using System.Linq; + using System.Reflection; + using System.Runtime.Versioning; using NUnit.Framework; @@ -20,6 +22,14 @@ public class IdentifierTestFixture { private const string VariantDigits = "89ab"; + [OneTimeSetUp] + public void OneTimeSetUp() + { + var targetFramework = typeof(Identifier).Assembly.GetCustomAttribute(); + + Assert.That(targetFramework?.FrameworkName, Is.EqualTo(".NETStandard,Version=v2.1")); + } + [Test] public void VerifyNewId() { diff --git a/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj b/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj index 5e973c61b..f8021e99c 100644 --- a/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj +++ b/SysML2.NET.Identifiers.Tests/SysML2.NET.Identifiers.Tests.csproj @@ -17,7 +17,7 @@ - + From 318b01e16a3d7542cbff5f3e649288e0611b0542 Mon Sep 17 00:00:00 2001 From: antoineatsoprasteria Date: Fri, 4 Dec 2026 14:38:41 +0100 Subject: [PATCH 3/3] Inline Guid version per spec --- .../UML/AutoGenSql/schema.generated.sql | 17 ++++++------- .../Sql/schema.golden.sql | 17 ++++++------- .../Templates/Uml/core-sql-schema.hbs | 17 ++++++------- SysML2.NET.Dal/AutoGenSql/0001_initial.sql | 17 ++++++------- .../IdentifierExtensionsTestFixture.cs | 6 +++++ .../PSM/DTO/PimMappingTestFixture.cs | 3 ++- SysML2.NET/Extensions/IdentifierExtensions.cs | 23 +++++++++++------- .../OptionallyIdentifiedExtensions.cs | 4 +++- .../PSM/DTO/Mapping/CommitRequest.Mapping.cs | 4 ++-- doc/SQLSCHEMA-GUIDE.md | 24 ++++++++++++------- doc/SQLSCHEMA.md | 2 +- 11 files changed, 79 insertions(+), 55 deletions(-) diff --git a/SysML2.NET.CodeGenerator.Tests/Expected/UML/AutoGenSql/schema.generated.sql b/SysML2.NET.CodeGenerator.Tests/Expected/UML/AutoGenSql/schema.generated.sql index 0043b9568..4de7628da 100644 --- a/SysML2.NET.CodeGenerator.Tests/Expected/UML/AutoGenSql/schema.generated.sql +++ b/SysML2.NET.CodeGenerator.Tests/Expected/UML/AutoGenSql/schema.generated.sql @@ -604,7 +604,7 @@ CREATE INDEX ix_data_identity_project_kind ON sysml2.data_identity (project_id, CREATE TABLE sysml2.element_version ( project_id uuid NOT NULL, - version_id uuid NOT NULL, -- DataVersion.id + version_id uuid NOT NULL DEFAULT gen_random_uuid(), -- DataVersion.id: random, version 4 (API Clause 7.1.2) identity_id uuid NOT NULL, -- FK via the composite typed-identity check below commit_id uuid NOT NULL REFERENCES sysml2.commit (id), class_kind smallint NOT NULL REFERENCES sysml2.class_kind (id), @@ -4274,21 +4274,22 @@ $$; -- PG18 OPPORTUNISTIC DEFAULTS (version-guarded; a no-op on the PostgreSQL 16/17 floor). -- --- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on every --- SERVER-MINTED key. Time-ordered ids turn each project's insert pattern into rightmost --- btree appends instead of random-page scatter (audit finding R8). The application-side --- Guid.CreateVersion7() remains the PRIMARY id source — the service usually needs the ids +-- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on the server-minted +-- keys that may be time-ordered. Time-ordered ids turn each project's insert pattern into +-- rightmost btree appends, not random-page scatter (audit finding R8). The application-side +-- Identifier.NewId() remains the PRIMARY id source — the service usually needs the ids -- before insert (to wire derived_id into branch_head etc.); these defaults are the safety -- net that keeps ad-hoc/tooling inserts time-ordered too. -- --- Deliberately NOT defaulted: data_identity.id (the spec-visible @id is supplied by the --- API layer or the client — a silent server default would mask missing-id bugs). +-- Deliberately NOT defaulted here: element_version.version_id (DataVersion.id is a random, +-- version 4 UUID, API Clause 7.1.2 — defaulted to gen_random_uuid() in §5) and +-- data_identity.id (the spec-visible @id is supplied by the API layer or the client — a +-- silent server default would mask missing-id bugs). DO $$ BEGIN IF current_setting('server_version_num')::int >= 180000 THEN - ALTER TABLE sysml2.element_version ALTER COLUMN version_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.derived_version ALTER COLUMN derived_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.project ALTER COLUMN id SET DEFAULT uuidv7(); ALTER TABLE sysml2.commit ALTER COLUMN id SET DEFAULT uuidv7(); diff --git a/SysML2.NET.CodeGenerator.Tests/Sql/schema.golden.sql b/SysML2.NET.CodeGenerator.Tests/Sql/schema.golden.sql index 7f3dc2201..92db6f5d2 100644 --- a/SysML2.NET.CodeGenerator.Tests/Sql/schema.golden.sql +++ b/SysML2.NET.CodeGenerator.Tests/Sql/schema.golden.sql @@ -435,7 +435,7 @@ CREATE INDEX ix_data_identity_project_kind ON sysml2.data_identity (project_id, CREATE TABLE sysml2.element_version ( project_id uuid NOT NULL, - version_id uuid NOT NULL, -- DataVersion.id + version_id uuid NOT NULL DEFAULT gen_random_uuid(), -- DataVersion.id: random, version 4 (API Clause 7.1.2) identity_id uuid NOT NULL, -- FK via the composite typed-identity check below commit_id uuid NOT NULL REFERENCES sysml2.commit (id), class_kind smallint NOT NULL REFERENCES sysml2.class_kind (id), @@ -1897,21 +1897,22 @@ $$; -- PG18 OPPORTUNISTIC DEFAULTS (version-guarded; a no-op on the PostgreSQL 16/17 floor). -- --- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on every --- SERVER-MINTED key. Time-ordered ids turn each project's insert pattern into rightmost --- btree appends instead of random-page scatter (audit finding R8). The application-side --- Guid.CreateVersion7() remains the PRIMARY id source — the service usually needs the ids +-- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on the server-minted +-- keys that may be time-ordered. Time-ordered ids turn each project's insert pattern into +-- rightmost btree appends, not random-page scatter (audit finding R8). The application-side +-- Identifier.NewId() remains the PRIMARY id source — the service usually needs the ids -- before insert (to wire derived_id into branch_head etc.); these defaults are the safety -- net that keeps ad-hoc/tooling inserts time-ordered too. -- --- Deliberately NOT defaulted: data_identity.id (the spec-visible @id is supplied by the --- API layer or the client — a silent server default would mask missing-id bugs). +-- Deliberately NOT defaulted here: element_version.version_id (DataVersion.id is a random, +-- version 4 UUID, API Clause 7.1.2 — defaulted to gen_random_uuid() in §5) and +-- data_identity.id (the spec-visible @id is supplied by the API layer or the client — a +-- silent server default would mask missing-id bugs). DO $$ BEGIN IF current_setting('server_version_num')::int >= 180000 THEN - ALTER TABLE sysml2.element_version ALTER COLUMN version_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.derived_version ALTER COLUMN derived_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.project ALTER COLUMN id SET DEFAULT uuidv7(); ALTER TABLE sysml2.commit ALTER COLUMN id SET DEFAULT uuidv7(); diff --git a/SysML2.NET.CodeGenerator/Templates/Uml/core-sql-schema.hbs b/SysML2.NET.CodeGenerator/Templates/Uml/core-sql-schema.hbs index e1bd986a3..898bd926f 100644 --- a/SysML2.NET.CodeGenerator/Templates/Uml/core-sql-schema.hbs +++ b/SysML2.NET.CodeGenerator/Templates/Uml/core-sql-schema.hbs @@ -415,7 +415,7 @@ CREATE INDEX ix_data_identity_project_kind ON sysml2.data_identity (project_id, CREATE TABLE sysml2.element_version ( project_id uuid NOT NULL, - version_id uuid NOT NULL, -- DataVersion.id + version_id uuid NOT NULL DEFAULT gen_random_uuid(), -- DataVersion.id: random, version 4 (API Clause 7.1.2) identity_id uuid NOT NULL, -- FK via the composite typed-identity check below commit_id uuid NOT NULL REFERENCES sysml2.commit (id), class_kind smallint NOT NULL REFERENCES sysml2.class_kind (id), @@ -1255,21 +1255,22 @@ $$; -- PG18 OPPORTUNISTIC DEFAULTS (version-guarded; a no-op on the PostgreSQL 16/17 floor). -- --- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on every --- SERVER-MINTED key. Time-ordered ids turn each project's insert pattern into rightmost --- btree appends instead of random-page scatter (audit finding R8). The application-side --- Guid.CreateVersion7() remains the PRIMARY id source — the service usually needs the ids +-- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on the server-minted +-- keys that may be time-ordered. Time-ordered ids turn each project's insert pattern into +-- rightmost btree appends, not random-page scatter (audit finding R8). The application-side +-- Identifier.NewId() remains the PRIMARY id source — the service usually needs the ids -- before insert (to wire derived_id into branch_head etc.); these defaults are the safety -- net that keeps ad-hoc/tooling inserts time-ordered too. -- --- Deliberately NOT defaulted: data_identity.id (the spec-visible @id is supplied by the --- API layer or the client — a silent server default would mask missing-id bugs). +-- Deliberately NOT defaulted here: element_version.version_id (DataVersion.id is a random, +-- version 4 UUID, API Clause 7.1.2 — defaulted to gen_random_uuid() in §5) and +-- data_identity.id (the spec-visible @id is supplied by the API layer or the client — a +-- silent server default would mask missing-id bugs). DO $$ BEGIN IF current_setting('server_version_num')::int >= 180000 THEN - ALTER TABLE sysml2.element_version ALTER COLUMN version_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.derived_version ALTER COLUMN derived_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.project ALTER COLUMN id SET DEFAULT uuidv7(); ALTER TABLE sysml2.commit ALTER COLUMN id SET DEFAULT uuidv7(); diff --git a/SysML2.NET.Dal/AutoGenSql/0001_initial.sql b/SysML2.NET.Dal/AutoGenSql/0001_initial.sql index 0043b9568..4de7628da 100644 --- a/SysML2.NET.Dal/AutoGenSql/0001_initial.sql +++ b/SysML2.NET.Dal/AutoGenSql/0001_initial.sql @@ -604,7 +604,7 @@ CREATE INDEX ix_data_identity_project_kind ON sysml2.data_identity (project_id, CREATE TABLE sysml2.element_version ( project_id uuid NOT NULL, - version_id uuid NOT NULL, -- DataVersion.id + version_id uuid NOT NULL DEFAULT gen_random_uuid(), -- DataVersion.id: random, version 4 (API Clause 7.1.2) identity_id uuid NOT NULL, -- FK via the composite typed-identity check below commit_id uuid NOT NULL REFERENCES sysml2.commit (id), class_kind smallint NOT NULL REFERENCES sysml2.class_kind (id), @@ -4274,21 +4274,22 @@ $$; -- PG18 OPPORTUNISTIC DEFAULTS (version-guarded; a no-op on the PostgreSQL 16/17 floor). -- --- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on every --- SERVER-MINTED key. Time-ordered ids turn each project's insert pattern into rightmost --- btree appends instead of random-page scatter (audit finding R8). The application-side --- Guid.CreateVersion7() remains the PRIMARY id source — the service usually needs the ids +-- On PostgreSQL 18+ the schema self-activates native uuidv7() defaults on the server-minted +-- keys that may be time-ordered. Time-ordered ids turn each project's insert pattern into +-- rightmost btree appends, not random-page scatter (audit finding R8). The application-side +-- Identifier.NewId() remains the PRIMARY id source — the service usually needs the ids -- before insert (to wire derived_id into branch_head etc.); these defaults are the safety -- net that keeps ad-hoc/tooling inserts time-ordered too. -- --- Deliberately NOT defaulted: data_identity.id (the spec-visible @id is supplied by the --- API layer or the client — a silent server default would mask missing-id bugs). +-- Deliberately NOT defaulted here: element_version.version_id (DataVersion.id is a random, +-- version 4 UUID, API Clause 7.1.2 — defaulted to gen_random_uuid() in §5) and +-- data_identity.id (the spec-visible @id is supplied by the API layer or the client — a +-- silent server default would mask missing-id bugs). DO $$ BEGIN IF current_setting('server_version_num')::int >= 180000 THEN - ALTER TABLE sysml2.element_version ALTER COLUMN version_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.derived_version ALTER COLUMN derived_id SET DEFAULT uuidv7(); ALTER TABLE sysml2.project ALTER COLUMN id SET DEFAULT uuidv7(); ALTER TABLE sysml2.commit ALTER COLUMN id SET DEFAULT uuidv7(); diff --git a/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs b/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs index 9c234c1a4..311cadbb0 100644 --- a/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs +++ b/SysML2.NET.Tests/Extensions/IdentifierExtensionsTestFixture.cs @@ -18,6 +18,7 @@ namespace SysML2.NET.Tests.Extensions using DtoPartUsage = SysML2.NET.Core.DTO.Systems.Parts.PartUsage; using PimCommit = SysML2.NET.PIM.DTO.Commit; + using PimDataVersion = SysML2.NET.PIM.DTO.DataVersion; using PocoPartUsage = SysML2.NET.Core.POCO.Systems.Parts.PartUsage; [TestFixture] @@ -32,6 +33,8 @@ public void VerifyAssignNewId() var project = new Project(); var pocoPart = new PocoPartUsage(); var dtoPart = new DtoPartUsage(); + var pimVersion = new PimDataVersion(); + var psmVersion = new DataVersion(); using (Assert.EnterMultipleScope()) { @@ -39,8 +42,11 @@ public void VerifyAssignNewId() Assert.That(commit.Id.ToString()[14], Is.EqualTo('7')); Assert.That(project.AssignNewId().Id, Is.Not.EqualTo(Guid.Empty)); Assert.That(pocoPart.AssignNewId().ElementId, Is.EqualTo(pocoPart.Id.ToString())); + Assert.That(pocoPart.Id.ToString()[14], Is.EqualTo('7')); Assert.That(dtoPart.AssignNewId().ElementId, Is.EqualTo(dtoPart.Id.ToString())); Assert.That(pocoPart.Id, Is.Not.EqualTo(dtoPart.Id)); + Assert.That(pimVersion.AssignNewId().Id.ToString()[14], Is.EqualTo('4')); + Assert.That(psmVersion.AssignNewId().Id.ToString()[14], Is.EqualTo('4')); } var identifier = commit.Id; diff --git a/SysML2.NET.Tests/PSM/DTO/PimMappingTestFixture.cs b/SysML2.NET.Tests/PSM/DTO/PimMappingTestFixture.cs index d60fdc6ce..3424b402a 100644 --- a/SysML2.NET.Tests/PSM/DTO/PimMappingTestFixture.cs +++ b/SysML2.NET.Tests/PSM/DTO/PimMappingTestFixture.cs @@ -542,7 +542,8 @@ public void VerifyCommitRequestRoundTrip() using (Assert.EnterMultipleScope()) { - Assert.That(commit.Id, Is.Not.EqualTo(Guid.Empty)); + Assert.That(commit.Id.ToString()[14], Is.EqualTo('7')); + Assert.That(change.Select(version => version.Id.ToString()[14]), Is.All.EqualTo('4')); Assert.That(commit.Alias, Is.EqualTo(TwoAliases)); Assert.That(commit.Name, Is.EqualTo(request.Name)); Assert.That(change, Has.Count.EqualTo(2)); diff --git a/SysML2.NET/Extensions/IdentifierExtensions.cs b/SysML2.NET/Extensions/IdentifierExtensions.cs index 1ade45b88..7527dd163 100644 --- a/SysML2.NET/Extensions/IdentifierExtensions.cs +++ b/SysML2.NET/Extensions/IdentifierExtensions.cs @@ -15,10 +15,12 @@ namespace SysML2.NET.Extensions using SysML2.NET.Identifiers; using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PimDataVersion = SysML2.NET.PIM.DTO.DataVersion; using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PsmDataVersion = SysML2.NET.PSM.DTO.DataVersion; /// - /// Extension methods that give new data its version 7 identifier + /// Extension methods that give new data its identifier /// public static class IdentifierExtensions { @@ -30,7 +32,8 @@ public static class IdentifierExtensions extension(T subject) where T : class, IIdentified { /// - /// Sets the of the subject, and the ElementId of an element, to a new + /// Sets the of the subject, and the ElementId of an element, to a new , + /// except a data version, which receives a random version 4 UUID (Systems Modeling API and Services §7.1.2) /// /// The subject. /// If the subject is null @@ -42,7 +45,9 @@ public T AssignNewId() throw new ArgumentNullException(nameof(subject)); } - var identifier = NewIdForUnidentified(subject.Id); + EnsureUnidentified(subject.Id); + + var identifier = subject is PimDataVersion or PsmDataVersion ? Guid.NewGuid() : Identifier.NewId(); switch (subject) { @@ -60,16 +65,16 @@ public T AssignNewId() } /// - /// Mints a new identifier for data that has none yet + /// Ensures that data has no identifier yet /// /// The identifier the data carries, null or when it has none. - /// A new version 7 . /// If is already an identifier - internal static Guid NewIdForUnidentified(Guid? current) + internal static void EnsureUnidentified(Guid? current) { - return current.GetValueOrDefault() == Guid.Empty - ? Identifier.NewId() - : throw new InvalidOperationException($"The data is already identified by {current}; an identifier never changes."); + if (current.GetValueOrDefault() != Guid.Empty) + { + throw new InvalidOperationException($"The data is already identified by {current}; an identifier never changes."); + } } } } diff --git a/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs b/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs index bf350a7ae..0e2cfb91f 100644 --- a/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs +++ b/SysML2.NET/Extensions/OptionallyIdentifiedExtensions.cs @@ -39,7 +39,9 @@ public T AssignNewId() throw new ArgumentNullException(nameof(request)); } - request.Id = IdentifierExtensions.NewIdForUnidentified(request.Id); + IdentifierExtensions.EnsureUnidentified(request.Id); + + request.Id = Identifier.NewId(); return request; } } diff --git a/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs b/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs index 84615c94c..f0f344d51 100644 --- a/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs +++ b/SysML2.NET/PSM/DTO/Mapping/CommitRequest.Mapping.cs @@ -13,6 +13,7 @@ namespace SysML2.NET.PSM.DTO using System.Collections.Generic; using System.Linq; + using SysML2.NET.Extensions; using SysML2.NET.Identifiers; /// @@ -51,8 +52,7 @@ public PIM.DTO.Commit ToPim() var change = (this.Change ?? []).Select(request => { - var version = request.ToPim(); - version.Id = Identifier.NewId(); + var version = request.ToPim().AssignNewId(); version.Commit = commit.Id; return version; }).ToList(); diff --git a/doc/SQLSCHEMA-GUIDE.md b/doc/SQLSCHEMA-GUIDE.md index 0e9671a53..494a36c72 100644 --- a/doc/SQLSCHEMA-GUIDE.md +++ b/doc/SQLSCHEMA-GUIDE.md @@ -862,8 +862,10 @@ Design notes, column by column: uuid without `project_id`** — turned out to matter enormously; section 14 (finding R2) shows what happens when you forget. - **`version_id` is the row's own identity** (the spec's `DataVersion.id`). It is - app-generated, and the audit recommends UUIDv7 (time-ordered) so each project's inserts land - on the rightmost btree leaf instead of splattering across the index (finding R8). + app-generated, and API Clause 7.1.2 makes it "a new, randomly generated UUID": version 4, + defaulted to `gen_random_uuid()`. The time-ordered UUIDv7 of finding R8 is therefore not + available here, and each project's inserts land at random positions within its range of the + index — the cost the UUIDv4-vs-v7 benchmark A/B measures. - **`class_kind` is a `smallint`, not a name.** 175 metaclass names are interned in the `class_kind` catalog (section 12). On the hottest, largest table in the database, that is a 2-byte column instead of a ~15-byte text one, times hundreds of millions of rows, times its @@ -1633,9 +1635,11 @@ precisely the O(model) operations: checkpoint builds, set reads, vacuum on the b The schema exploits 18 automatically where it can, and the rest is deployment guidance: - **Self-activating `uuidv7()` defaults** (implemented, §12): a version-guarded `DO` block - sets `DEFAULT uuidv7()` on every server-minted key (`version_id`, `derived_id`, and the + sets `DEFAULT uuidv7()` on the time-orderable server-minted keys (`derived_id` and the PIM record ids) when `server_version_num >= 180000` — a verified no-op on the 16/17 floor. - `Guid.CreateVersion7()` in the service remains the primary id source (the service needs + `version_id` is excluded: it is `DataVersion.id`, version 4 by API Clause 7.1.2, and carries + `DEFAULT gen_random_uuid()` on every version. + `Identifier.NewId()` in the service remains the primary id source (the service needs ids before insert); the defaults are the safety net that keeps ad-hoc and tooling inserts time-ordered. `data_identity.id` is deliberately excluded — the spec-visible `@id` must be supplied, never silently minted. @@ -1669,10 +1673,12 @@ Physical decisions that came out of the audit: - **lz4 for the jsonb columns**, set on the parents *before* the partition loop so leaves inherit it (verified in `pg_attribute`). At this write volume, pglz compression cost is measurable on every commit; lz4 is strictly better here. -- **UUIDv7 for app-generated keys** (`version_id`, `derived_id`): time-ordered uuids turn each - project's insert pattern from random-page btree scatter into rightmost-leaf appends. A .NET - note (`Guid.CreateVersion7()`), not a schema change. `identity_id` stays as supplied — it is - the spec-visible `@id` (and library elements are normatively v5). +- **UUIDv7 for app-generated keys** (`derived_id` and the PIM record ids): time-ordered uuids + turn each project's insert pattern from random-page btree scatter into rightmost-leaf + appends. A .NET note (`Identifier.NewId()`), not a schema change. `version_id` is + `DataVersion.id`, which API Clause 7.1.2 makes a random UUID (version 4), so its inserts keep + the random pattern. `identity_id` stays as supplied — it is the spec-visible `@id` (and + library elements are normatively v5). - **Bulk import**: the ~3 FK probes per inserted row against a 10⁸-row `data_identity` are real but modest; if measurement demands it, the importer path is `SET session_replication_role = replica` plus post-import validation queries. The audit @@ -2289,7 +2295,7 @@ sections** (not the schema files' § banners); "—" means the term is used only | **TPT (table-per-type)** | One table per class, joined along inheritance; rejected — the DAG breaks the chain. | 5.2 | | **Typed identity** | `data_identity.class_kind`: the element's immutable metaclass on the identity row, making type FK-able where versions never are — enforced on every version by a composite FK. | 7 | | **Upsert (`ON CONFLICT`)** | Insert-or-update in one statement; how commits maintain the overlay. | 10.2, 18.2 | -| **UUID v4 / v5 / v7** | Random / name-based / time-ordered uuids; v7 recommended for app-generated keys (self-activated as `DEFAULT uuidv7()` on PG18), v5 normative for library elementIds. | 7, 13 | +| **UUID v4 / v5 / v7** | Random / name-based / time-ordered uuids; v4 normative for `DataVersion.id` (`version_id`, API Clause 7.1.2), v7 for the other app-generated keys (self-activated as `DEFAULT uuidv7()` on PG18), v5 normative for library elementIds. | 7, 8.1, 13 | | **Version** | One element's stored state as of one commit; an `element_version` row; immutable. | 4, 8.1 | | **WAL** | PostgreSQL's write-ahead log — the durability cost of every write. | 14 | | **XMI** | XML Metadata Interchange — the UML files that are the metamodel's source of truth for generation. | 2, 17 | diff --git a/doc/SQLSCHEMA.md b/doc/SQLSCHEMA.md index 7134e54e1..0a5b3b4bb 100644 --- a/doc/SQLSCHEMA.md +++ b/doc/SQLSCHEMA.md @@ -177,7 +177,7 @@ ranked; all SEV-1/2 fixes are implemented in the schema, the policy items are sp | R5 | 2 | Worst-case derived burst (root rename ≈ 1M multi-KB jsonb rows) × whole-document GIN | **Partially fixed**: lz4 on `stored_json`/`derived_json` (verified inherited by leaves). Bulk derived writes: raise `gin_pending_list_limit` (≥64MB) for the session + `gin_clean_pending_list()` after. GIN stays (spec requires arbitrary-property constraints); revisit as expression indexes if the Query service's filtered-property set proves narrow. | | R6 | 2 | Single-element historical read folded the whole model | **Fixed**: `resolve_element_at_commit()` / `get_element_at_commit()` — O(walked ancestry). | | R7 | 3 | Link-table write amplification: a new version re-inserts the element's whole collection (pathological for 100k-child packages) | **Documented, conditional**: content-addressed collections (`collection_id` digest on `element_version`, shared ordered rows) if benchmarks fail; reshapes generated tables. | -| R8 | 3 | Random UUID PKs fragment per-project index ranges | **.NET note**: generate `version_id`/`derived_id` as UUIDv7 (`Guid.CreateVersion7()`); on PG18 the schema additionally self-activates `DEFAULT uuidv7()` on all server-minted keys (version-guarded DO block, no-op on 16/17). `identity_id` is spec-visible, stays as supplied (library elements are normatively v5). | +| R8 | 3 | Random UUID PKs fragment per-project index ranges | **.NET note**: generate `derived_id` and the PIM record ids as UUIDv7 (`Identifier.NewId()`); on PG18 the schema additionally self-activates `DEFAULT uuidv7()` on those server-minted keys (version-guarded DO block, no-op on 16/17). **`version_id` is version 4**: it is `DataVersion.id`, "a new, randomly generated UUID" (API Clause 7.1.2), defaulted to `gen_random_uuid()` — so R8 does not apply to `element_version`, whose inserts land at random positions within each project's range of the `(project_id, version_id)` index; the UUIDv4-vs-v7 A/B measures that cost. `identity_id` is spec-visible, stays as supplied (library elements are normatively v5). | | R9 | 3 | One-size autovacuum for opposite write profiles | **Fixed**: `branch_head` leaves get `fillfactor 90` + analyze@50k; append-only leaves get insert-driven vacuum (100k) + analyze@50k. | | R10 | 3 | Generic-plan flips and fast-path lock exhaustion on the 6-join views | **Ops checklist**: prefer PG18 where available (btree skip scan, AIO, `NOT VALID` FKs on partitioned tables, native `uuidv7()`), else PG17 (fast-path slots scale with `max_locks_per_transaction`); verify hot plans show "Subplans Removed: 15"; pin `plan_cache_mode = force_custom_plan` on Query-service pools if generic plans misbehave. | | R11 | 3 | Bulk-import FK probes (~3M/1M elements). `DEFERRABLE` REJECTED (defers, doesn't reduce); `NOT VALID` needs PG18 on partitioned tables | **Documented**: measure first; importer may use `SET session_replication_role = replica` + post-import validation queries; or raise the floor to PG18 for `NOT VALID`+`VALIDATE`. |