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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ operations fail explicitly. See [extension schema contracts](docs/metadata-facad
for examples, output mapping, and round-trip limitations.

`IPlan.Metadata` preserves plan-level advanced extensions, the ordered
`expected_type_urls`, and imported extension URN/declaration tables. Export keeps
`expected_type_urls`, imported extension URN/declaration tables, `type_aliases`,
and `parameter_bindings`. `IPlan.ExecutionBehavior` holds the required
`execution_behavior`. Export keeps
all imported anchors, including aliases and apparently unused dependencies that
opaque payloads may reference. Core references use one existing anchor per
identity; new dependencies receive nonconflicting anchors.
Expand All @@ -185,7 +187,7 @@ var schema = new NamedStruct(
["order_id"], TypeFactory.REQUIRED.Struct([TypeFactory.REQUIRED.I64]));
var orders = new NamedTableRead(schema, ["orders"], filter: null);

var builder = new PlanBuilder();
var builder = new PlanBuilder(new ExecutionBehavior(VariableEvaluationMode.PerPlan));
Reference sharedOrders = builder.RegisterSubplan(orders); // Entry 0, not an output.
builder.AddRoot(sharedOrders, ["all_order_ids"]); // Entry 1.
builder.AddRoot(
Expand Down
6 changes: 2 additions & 4 deletions docs/alias-references.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,5 @@ implementation to keep compiling.
**resolution**: defining aliases, resolving references against an alias
table, missing-target checks, and cycle detection are
[`TypeAliasTable`](alias-resolution.md)'s job, not this type's.
- Storing or emitting `Plan.type_aliases` belongs to
[substrait-io/substrait-csharp#27](https://github.com/substrait-io/substrait-csharp/issues/27).
This slice supplies the reference model that work needs, independent of
the full plan envelope.
- Plan conversion stores and emits `Plan.type_aliases` as
`PlanMetadata.TypeAliases`; see [type-alias resolution](alias-resolution.md).
11 changes: 4 additions & 7 deletions docs/alias-resolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,10 @@ creates a fresh one, for standalone use.

## Boundaries

- This slice owns alias-definition models and table validation/resolution,
independent of the full plan envelope. Retaining `Plan.type_aliases` on
the internal `Plan`/`PlanMetadata` model, and invoking this table from
`ProtoToPlanConverter`/`PlanToProtoConverter`, belongs to
[substrait-io/substrait-csharp#27](https://github.com/substrait-io/substrait-csharp/issues/27).
Until that lands, `ProtoToPlanConverter` explicitly rejects any plan
declaring `Plan.type_aliases` rather than silently dropping the table.
- `ProtoToPlanConverter` reads `Plan.type_aliases` into
`PlanMetadata.TypeAliases` and rejects any alias reference whose anchor the
plan does not declare; `PlanToProtoConverter` writes the table back through
the plan's shared context. References in the plan stay unresolved.
- Extension YAML type variables/type classes remain out of scope here; see
[substrait-io/substrait-csharp#46](https://github.com/substrait-io/substrait-csharp/issues/46).
Alias anchors are a separate namespace from extension type anchors.
14 changes: 7 additions & 7 deletions docs/metadata-facades.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ using Substrait.Core.Type;
var schema = new Substrait.Core.Type.NamedStruct(
["order_id"], TypeFactory.REQUIRED.Struct([TypeFactory.REQUIRED.I64]));
var orders = new NamedTableRead(schema, ["orders"], filter: null);
var builder = new PlanBuilder();
var builder = new PlanBuilder(new ExecutionBehavior(VariableEvaluationMode.PerPlan));
builder.AddRoot(orders, ["order_id"]);
var configuration = new StringValue { Value = "required configuration" };
builder.SetEnhancement(configuration);
Expand Down Expand Up @@ -325,7 +325,7 @@ unchanged. An unchanged `Build()` reuses the current metadata rather than
recopying it. Editing an advanced-extension field preserves the other fields
and unknown protobuf fields. Expected type URLs are edited independently and
are never inferred from payloads. All these edits also preserve the declaration
tables. Builders are not thread-safe.
tables, type aliases, and parameter bindings. Builders are not thread-safe.

Setting or adding a payload creates the advanced-extension message if absent.
Removing the last payload leaves a present empty message; only
Expand All @@ -337,11 +337,11 @@ Callers with existing immutable metadata can still construct `PlanMetadata` from
a `ReadOnlyAdvancedExtension` or a protobuf `AdvancedExtension`. The protobuf
constructor snapshots the entire message, including nested payloads and unknown
fields. That metadata can be supplied to
`new Plan(metadata, roots, version)` or
`Plan.FromRelations(metadata, relations, version)`, or used as the starting point
for `new PlanBuilder(metadata, version)`. The builder's metadata-first overload
requires an explicit `version` argument (null selects the current version), so
the existing `new PlanBuilder(null)` call remains unambiguous.
`new Plan(metadata, roots, version, executionBehavior)` or
`Plan.FromRelations(metadata, relations, version, executionBehavior)`, or used as
the starting point for `new PlanBuilder(metadata, version, executionBehavior)`.
The builder's metadata-first overload requires explicit `version` and
`executionBehavior` arguments (a null version selects the current version).

The four-argument facade constructor additionally accepts `extensionUrns` and
`extensions`. Null collections mean empty lists; null elements are rejected.
Expand Down
7 changes: 4 additions & 3 deletions docs/preview-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,14 @@ including to a root's input, and form acyclic chains or shared DAGs.
- Custom `IPlan` implementations must implement the new `Relations` property
and recompile. `IRoot.Input` is now inherited from `IRelation` rather than
declared directly on `IRoot`; this is an approved preview API change.
- Existing `new Plan(IEnumerable<IPlan.IRoot>, IVersion)` and `Plan.Root`
- Existing `new Plan(IEnumerable<IPlan.IRoot>, IVersion, ExecutionBehavior)` and `Plan.Root`
construction remain available. `IPlan.Roots` remains an ordered root-only
projection; its indexes are **not** subtree ordinals.
- Use `Plan.Relation(IRel input)` for non-root entries and
`Plan.FromRelations(IEnumerable<IPlan.IRelation>, IVersion)` for mixed
`Plan.FromRelations(IEnumerable<IPlan.IRelation>, IVersion, ExecutionBehavior)` for mixed
advanced composition. The factory snapshots the supplied entry list.
- `new PlanBuilder(IVersion? version = null)` defaults to `Version.Current`.
- `new PlanBuilder(ExecutionBehavior, IVersion? version = null)` defaults the
version to `Version.Current`; the execution behavior is required.
`RegisterSubplan(IRel)` appends a non-root entry and returns a `Reference`;
`AddRoot(IRel, IEnumerable<string>)` appends a root and also returns a
`Reference`, allowing later entries to reference that root's input.
Expand Down
7 changes: 4 additions & 3 deletions docs/type-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,13 @@ collections.
| Unspecified nullability | `NotImplementedException`; `SerializationException` for `user_defined` | `SerializationException` naming the path |
| Undeclared variation anchor | `SerializationException` | `SerializationException` naming the path |
| Out-of-range parameter | `ArgumentOutOfRangeException` | `SerializationException` naming the path |
| Alias anchor not in the plan's `type_aliases` (plan import only) | `ArgumentException` | `ArgumentException` |

## Boundaries

- `ProtoToPlanConverter` rejects plans that declare `Plan.type_aliases`; full
plan-envelope alias retention belongs to
[substrait-io/substrait-csharp#27](https://github.com/substrait-io/substrait-csharp/issues/27).
- `ProtoToPlanConverter` retains `Plan.type_aliases` as `PlanMetadata.TypeAliases`
and rejects an alias reference whose anchor the plan does not declare.
Standalone type conversion does not check alias anchors.
- Extension YAML type expressions and type classes belong to
[substrait-io/substrait-csharp#46](https://github.com/substrait-io/substrait-csharp/issues/46).
- Coverage uses small synthetic fixtures. An upstream conformance corpus and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public override ProtoExpression Visit(UserDefinedLiteral expression, PlanToProto
var userDefined = new ProtoLiteral.Types.UserDefined();
if (expression.Type is ParameterizedType.AliasReference alias)
{
context.ValidateTypeAlias(alias.Anchor);
userDefined.TypeAliasReference = alias.Anchor;
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ public Literal CreateLiteral(ProtoLiteral protoLiteral)
throw new SerializationException("User-defined literal with a type alias reference cannot set type parameters.");
}

this.lookup.ValidateTypeAlias(current.UserDefined.TypeAliasReference);

if (current.UserDefined.Struct is not null)
{
destination.Add(new Literal.UserDefinedLiteral(current.UserDefined.TypeAliasReference, inputs, nullable) { TypeVariation = variation });
Expand Down
22 changes: 20 additions & 2 deletions src/Substrait/Core/Extension/ExtensionsDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ public sealed class ExtensionsDictionary
private readonly IReadOnlyDictionary<uint, TypeAnchor> typeAnchorMap;
private readonly IReadOnlyDictionary<int, TypeVariationImplAnchor> typeVariationAnchorMap;
private readonly IReadOnlyDictionary<int, FunctionImplAnchor> functionAnchorMap;
private readonly ImmutableHashSet<uint>? typeAliasAnchors;

private ExtensionsDictionary(
IEnumerable<KeyValuePair<uint, TypeAnchor>> typeAnchorMap,
IEnumerable<KeyValuePair<int, TypeVariationImplAnchor>> typeVariationAnchorMap,
IEnumerable<KeyValuePair<int, FunctionImplAnchor>> functionAnchorMap)
IEnumerable<KeyValuePair<int, FunctionImplAnchor>> functionAnchorMap,
IEnumerable<uint>? typeAliasAnchors)
{
this.typeAnchorMap = typeAnchorMap.ToImmutableDictionary();
this.typeVariationAnchorMap = typeVariationAnchorMap.ToImmutableDictionary();
this.functionAnchorMap = functionAnchorMap.ToImmutableDictionary();
this.typeAliasAnchors = typeAliasAnchors?.ToImmutableHashSet();
}

/// <summary>
Expand Down Expand Up @@ -58,6 +61,14 @@ public TypeAnchor GetTypeAnchor(uint reference) =>
/// <summary>Tries to get a declared type identity.</summary>
public bool TryGetTypeAnchor(uint reference, out TypeAnchor? anchor) => this.typeAnchorMap.TryGetValue(reference, out anchor);

internal void ValidateTypeAlias(uint reference)
{
if (this.typeAliasAnchors is not null && !this.typeAliasAnchors.Contains(reference))
{
throw new ArgumentException($"Invalid type alias ID: {reference}. Verify that the ID is included in the plan's type aliases section.");
}
}

/// <summary>Resolves an extension type definition.</summary>
public bool TryGetType(TypeAnchor anchor, ExtensionsCollection extensions, StrictMode strictMode, out TypeDefinition? type) =>
extensions.TryGetType(anchor, strictMode, out type);
Expand Down Expand Up @@ -131,6 +142,7 @@ public sealed class Builder
private readonly IDictionary<uint, TypeAnchor> typeMap = new Dictionary<uint, TypeAnchor>();
private readonly IDictionary<int, TypeVariationImplAnchor> typeVariationMap = new Dictionary<int, TypeVariationImplAnchor>();
private readonly IDictionary<int, FunctionImplAnchor> functionMap = new Dictionary<int, FunctionImplAnchor>();
private IEnumerable<uint>? typeAliasAnchors;

/// <summary>Initializes an empty builder.</summary>
public Builder()
Expand Down Expand Up @@ -179,11 +191,17 @@ private Builder(IEnumerable<SimpleExtensionURN> extensionUrns, IEnumerable<Simpl
}
}

internal Builder RequireTypeAliases(IEnumerable<uint> anchors)
{
this.typeAliasAnchors = anchors.ToImmutableList();
return this;
}

/// <summary>Builds the extension dictionary.</summary>
/// <returns>The extension dictionary.</returns>
public ExtensionsDictionary Build()
{
return new ExtensionsDictionary(this.typeMap, this.typeVariationMap, this.functionMap);
return new ExtensionsDictionary(this.typeMap, this.typeVariationMap, this.functionMap, this.typeAliasAnchors);
}

private static string GetNamespace(IReadOnlyDictionary<int, string> namespaceMap, int reference)
Expand Down
41 changes: 41 additions & 0 deletions src/Substrait/Core/Metadata/DynamicParameterBinding.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: Apache-2.0

using Substrait.Core.Expression;

namespace Substrait.Core.Metadata;

/// <summary>
/// The runtime value bound to a dynamic parameter.
/// </summary>
public sealed class DynamicParameterBinding : IEquatable<DynamicParameterBinding>
{
/// <summary>
/// Initializes a new instance of the <see cref="DynamicParameterBinding"/> class.
/// </summary>
/// <param name="parameterAnchor">The anchor of the bound dynamic parameter. 0 is a valid anchor.</param>
/// <param name="value">The bound value.</param>
public DynamicParameterBinding(uint parameterAnchor, Literal value)
{
this.ParameterAnchor = parameterAnchor;
this.Value = value ?? throw new ArgumentNullException(nameof(value));
}

/// <summary>
/// Gets the anchor of the bound dynamic parameter.
/// </summary>
public uint ParameterAnchor { get; }

/// <summary>
/// Gets the bound value.
/// </summary>
public Literal Value { get; }

/// <inheritdoc/>
public bool Equals(DynamicParameterBinding? other) => other is not null && this.ParameterAnchor == other.ParameterAnchor && this.Value.Equals(other.Value);

/// <inheritdoc/>
public override bool Equals(object? obj) => this.Equals(obj as DynamicParameterBinding);

/// <inheritdoc/>
public override int GetHashCode() => HashCode.Combine(nameof(DynamicParameterBinding), this.ParameterAnchor, this.Value);
}
56 changes: 51 additions & 5 deletions src/Substrait/Core/Metadata/PlanMetadata.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
// SPDX-License-Identifier: Apache-2.0

using System.Collections.Immutable;
using Substrait.Core.Type;
using Substrait.Protobuf;
using Substrait.Tools;

namespace Substrait.Core.Metadata;

/// <summary>Immutable plan-level extensions, declaration tables, and expected payload type URLs.</summary>
/// <summary>Immutable plan-level extensions, declaration tables, type aliases, dynamic parameter bindings, and expected payload type URLs.</summary>
public sealed class PlanMetadata : IEquatable<PlanMetadata>
{
/// <summary>Initializes metadata from an immutable facade and snapshots the expected type URLs.</summary>
Expand All @@ -27,11 +28,31 @@ public PlanMetadata(
IEnumerable<string>? expectedTypeUrls,
IEnumerable<ReadOnlySimpleExtensionURN>? extensionUrns,
IEnumerable<ReadOnlySimpleExtensionDeclaration>? extensions)
: this(advancedExtensions, expectedTypeUrls, extensionUrns, extensions, null, null)
{
}

/// <summary>Initializes metadata with retained declaration tables, type aliases, and dynamic parameter bindings.</summary>
/// <param name="advancedExtensions">Plan-level extensions, or null to preserve absence.</param>
/// <param name="expectedTypeUrls">Expected payload type URLs, or null for an empty list.</param>
/// <param name="extensionUrns">Immutable URN declarations, or null for an empty table.</param>
/// <param name="extensions">Immutable extension declarations, or null for an empty table.</param>
/// <param name="typeAliases">Type alias definitions, or null for an empty table.</param>
/// <param name="parameterBindings">Dynamic parameter bindings, or null for none. Order is preserved; anchors must be unique.</param>
public PlanMetadata(
ReadOnlyAdvancedExtension? advancedExtensions,
IEnumerable<string>? expectedTypeUrls,
IEnumerable<ReadOnlySimpleExtensionURN>? extensionUrns,
IEnumerable<ReadOnlySimpleExtensionDeclaration>? extensions,
TypeAliasTable? typeAliases,
IEnumerable<DynamicParameterBinding>? parameterBindings)
{
this.AdvancedExtensions = advancedExtensions;
this.ExpectedTypeUrls = expectedTypeUrls?.ToImmutableList() ?? ImmutableList<string>.Empty;
this.ExtensionUrns = extensionUrns?.ToImmutableList() ?? ImmutableList<ReadOnlySimpleExtensionURN>.Empty;
this.Extensions = extensions?.ToImmutableList() ?? ImmutableList<ReadOnlySimpleExtensionDeclaration>.Empty;
this.TypeAliases = typeAliases ?? TypeAliasTable.Empty;
this.ParameterBindings = parameterBindings?.ToImmutableList() ?? ImmutableList<DynamicParameterBinding>.Empty;
if (this.ExpectedTypeUrls.Any(value => value is null))
{
throw new ArgumentException("Expected type URLs must not contain null values.", nameof(expectedTypeUrls));
Expand All @@ -41,6 +62,20 @@ public PlanMetadata(
{
throw new ArgumentException("Extension declaration tables must not contain null values.");
}

if (this.ParameterBindings.Any(value => value is null))
{
throw new ArgumentException("Dynamic parameter bindings must not contain null values.", nameof(parameterBindings));
}

var anchors = new HashSet<uint>();
foreach (DynamicParameterBinding binding in this.ParameterBindings)
{
if (!anchors.Add(binding.ParameterAnchor))
{
throw new ArgumentException($"Duplicate dynamic parameter anchor {binding.ParameterAnchor}.", nameof(parameterBindings));
}
}
}

/// <summary>Initializes metadata by snapshotting a protobuf advanced-extension message.</summary>
Expand All @@ -66,25 +101,36 @@ public PlanMetadata(AdvancedExtension message, IEnumerable<string>? expectedType
/// <summary>Gets retained extension declarations. Opaque payloads may reference any of their anchors.</summary>
public IReadOnlyList<ReadOnlySimpleExtensionDeclaration> Extensions { get; }

/// <summary>Gets the type alias definitions that alias references in the plan resolve against.</summary>
public TypeAliasTable TypeAliases { get; }

/// <summary>Gets the dynamic parameter bindings in their original order.</summary>
public IReadOnlyList<DynamicParameterBinding> ParameterBindings { get; }

/// <inheritdoc/>
public bool Equals(PlanMetadata? other) => other is not null
&& Equals(this.AdvancedExtensions, other.AdvancedExtensions)
&& this.ExpectedTypeUrls.SequenceEqual(other.ExpectedTypeUrls, StringComparer.Ordinal)
&& this.ExtensionUrns.SequenceEqual(other.ExtensionUrns)
&& this.Extensions.SequenceEqual(other.Extensions);
&& this.Extensions.SequenceEqual(other.Extensions)
&& this.TypeAliases.Equals(other.TypeAliases)
&& this.ParameterBindings.SequenceEqual(other.ParameterBindings);

/// <inheritdoc/>
public override bool Equals(object? obj) => obj is PlanMetadata other && this.Equals(other);

/// <inheritdoc/>
public override int GetHashCode() => HashCode.Combine(
this.AdvancedExtensions, this.ExpectedTypeUrls.CombineHashCodes(),
this.ExtensionUrns.CombineHashCodes(), this.Extensions.CombineHashCodes());
this.ExtensionUrns.CombineHashCodes(), this.Extensions.CombineHashCodes(),
this.TypeAliases, this.ParameterBindings.CombineHashCodes());

internal static PlanMetadata Capture(Protobuf.Plan plan, bool owned) =>
internal static PlanMetadata Capture(Protobuf.Plan plan, bool owned, TypeAliasTable typeAliases, IEnumerable<DynamicParameterBinding> parameterBindings) =>
new(
RelationMetadata.CaptureExtension(plan.AdvancedExtensions, owned),
plan.ExpectedTypeUrls,
plan.ExtensionUrns.Select(value => owned ? ReadOnlySimpleExtensionURN.FromOwnedProto(value) : ReadOnlySimpleExtensionURN.FromProto(value)),
plan.Extensions.Select(value => owned ? ReadOnlySimpleExtensionDeclaration.FromOwnedProto(value) : ReadOnlySimpleExtensionDeclaration.FromProto(value)));
plan.Extensions.Select(value => owned ? ReadOnlySimpleExtensionDeclaration.FromOwnedProto(value) : ReadOnlySimpleExtensionDeclaration.FromProto(value)),
typeAliases,
parameterBindings);
}
Loading
Loading