Skip to content

[WIP] Add Configuration references#129734

Draft
rosebyte wants to merge 2 commits into
dotnet:mainfrom
rosebyte:configuration-references
Draft

[WIP] Add Configuration references#129734
rosebyte wants to merge 2 commits into
dotnet:mainfrom
rosebyte:configuration-references

Conversation

@rosebyte

Copy link
Copy Markdown
Member

No description provided.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-extensions-configuration
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a new “configuration references” feature for Microsoft.Extensions.Configuration, enabling configuration values to be expanded via reference syntax (e.g., ref(Target:Key)) and composed values (e.g., format(template, key1, key2, ...)). It does so by adding a contextual configuration source/provider that materializes expanded values on top of upstream providers, plus a fairly comprehensive new test suite.

Changes:

  • Adds a new reference rule model + pattern matcher (ReferenceRule, KeyPattern) and a contextual configuration provider (ReferenceConfigurationProvider) to materialize expanded values and mirror subtrees.
  • Extends ConfigurationBuilder and ConfigurationManager to support building “contextual” configuration sources that require an upstream provider snapshot.
  • Introduces new public API surface (AllowReferences, ConfigurationReferenceBuilder, ConfigurationExpansion) and adds end-to-end tests.

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
src/libraries/Microsoft.Extensions.Configuration/tests/ConfigurationReferenceTests.cs New test coverage for reference resolution, templates, composition, reload behavior, and parsing.
src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx Adds new user-facing error strings for reference expansion and validation.
src/libraries/Microsoft.Extensions.Configuration/src/ReferenceRule.cs Defines rule semantics (subject + allowed/denied targets) and validates parser output.
src/libraries/Microsoft.Extensions.Configuration/src/ReferenceConfigurationSource.cs Contextual source that requires upstream provider snapshot to build its provider.
src/libraries/Microsoft.Extensions.Configuration/src/ReferenceConfigurationProvider.cs Core implementation: resolves references, mirrors subtrees, composes format expansions, handles reload.
src/libraries/Microsoft.Extensions.Configuration/src/ReferenceConfigurationBuilderExtensions.cs Public builder extension method AllowReferences(...).
src/libraries/Microsoft.Extensions.Configuration/src/KeyPattern.cs Wildcard/doublestar key-pattern matching for subjects/targets.
src/libraries/Microsoft.Extensions.Configuration/src/IContextualConfigurationSource.cs Internal contract to allow sources to build with upstream provider list.
src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationReferenceBuilder.cs Public builder object for declaring rules and customizing the parser.
src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs Adds contextual-source dispatch when adding/reloading sources.
src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationExpansion.cs Public struct representing expansion kinds (reference/literal/format) returned by parsers.
src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs Adds contextual-source dispatch during build.
src/libraries/Microsoft.Extensions.Configuration/ref/Microsoft.Extensions.Configuration.cs Updates public API contract to include the new APIs/types.

Comment on lines +52 to +62
public static ConfigurationExpansion Format(string template, params string[] referencedKeys)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(referencedKeys);
return new ConfigurationExpansion(template, referencedKeys.Length switch
{
0 => StringValues.Empty,
1 => new StringValues(referencedKeys[0]),
_ => new StringValues(referencedKeys),
});
}
Comment on lines +180 to +184
[Fact]
public void Configurable_ValidSelection_ResolvesThrough()
{
IConfigurationRoot root = BuilderWith(Dict(
("Shared:Prod:Credential", "prod"),
Comment on lines +9 to +13
public sealed partial class ConfigurationReferenceBuilder
{
internal ConfigurationReferenceBuilder() { }
public Microsoft.Extensions.Configuration.ConfigurationReferenceBuilder Allow(string subject, string target, params string[] additionalTargets) { throw null; }
public Microsoft.Extensions.Configuration.ConfigurationReferenceBuilder Deny(string subject, string target, params string[] additionalTargets) { throw null; }
Comment on lines +43 to +49
ReferenceRule rule = FindOrCreateRule(NormaliseSubject(subject));
rule.AddTarget(NormaliseTarget(target));
foreach (string additionalTarget in additionalTargets)
{
rule.AddTarget(NormaliseTarget(additionalTarget));
}
return this;
Comment on lines +67 to +73
ReferenceRule rule = FindOrCreateRule(NormaliseSubject(subject));
rule.AddDisallowedTarget(NormaliseTarget(target));
foreach (string additionalTarget in additionalTargets)
{
rule.AddDisallowedTarget(NormaliseTarget(additionalTarget));
}
return this;
Comment on lines +389 to +405
// Reads the value already materialised for <paramref name="key"/> if any; otherwise
// falls back to the first non-empty upstream literal at the same key.
private string? OverlayAwareRead(string key, Dictionary<string, string?> values)
{
if (values.TryGetValue(key, out string? ov))
{
return ov;
}
for (int i = _upstream.Count - 1; i >= 0; i--)
{
if (_upstream[i].TryGet(key, out string? pv) && !string.IsNullOrEmpty(pv))
{
return pv;
}
}
return null;
}
Comment on lines +325 to +335
// A non-empty upstream literal at the overlay key should win on read;
// skip the overlay entry so it does.
string? sourceAtOverlay = ReadUpstream(overlayKey);
if (string.IsNullOrEmpty(sourceAtOverlay))
{
string? targetValue = OverlayAwareRead(childKey, values);
if (targetValue is not null)
{
values[overlayKey] = targetValue;
}
}
Comment on lines +141 to +146
<data name="Error_ReferenceTargetsRequired" xml:space="preserve">
<value>At least one non-empty reference target must be provided.</value>
</data>
<data name="Error_ReferenceTargetInvalid" xml:space="preserve">
<value>'{0}' is not a valid reference target pattern. Each ':'-separated segment must be non-empty; '*' is permitted only as a whole segment.</value>
</data>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 4 comments.

Comment on lines +636 to +645
private void OnUpstreamChanged()
{
if (!_disposed)
{
// Upstream changed, so the materialised state may be stale; drop it, then propagate so
// consumers re-read and re-materialise.
_valid = false;
OnReload();
}
}
Comment on lines +53 to +59
// Configuration expansion is opt-out: unless disabled, append a reference provider at the
// last position so it sees every source and its resolved values win on read. Skipped when
// there are no sources so an empty builder still reports "no sources" on write.
if (providers.Count > 0 && ConfigurationExpansionSwitch.Enabled)
{
providers.Add(new ReferenceConfigurationProvider(providers.ToArray()));
}
Comment on lines +261 to +263
private static InvalidOperationException ParseError(string whole) =>
new InvalidOperationException(SR.Format(SR.Error_ReferenceMarkerInvalid, whole));
}
@rosebyte
rosebyte force-pushed the configuration-references branch from 494bd94 to d34a11b Compare July 14, 2026 14:02
Copilot AI review requested due to automatic review settings July 16, 2026 07:49
@rosebyte
rosebyte force-pushed the configuration-references branch from d34a11b to 8082ba9 Compare July 16, 2026 07:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.

Comment on lines +20 to +22
// A leading backslash escapes a marker (\ref(...) / \format(...)) and yields the literal text with the
// backslash removed. Any other value is taken verbatim, and a direct non-empty value always wins over a
// value inherited through an ancestor reference.
Comment thread src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx Outdated
Copilot AI review requested due to automatic review settings July 16, 2026 10:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 11 out of 11 changed files in this pull request and generated 3 comments.

Comment on lines +20 to +22
// A leading backslash escapes a marker (\ref(...) / \format(...)) and yields the literal text with the
// backslash removed. Any other value is taken verbatim, and a direct non-empty value always wins over a
// value inherited through an ancestor reference.
Comment on lines +31 to +33
// Upper bound on reference hops in a single resolution. Real configurations chain references a handful of
// levels deep at most; exceeding this indicates a self-feeding reference that would otherwise never settle.
private const int MaxDepth = 100;
Comment on lines +123 to +128
<data name="Error_ReferenceComposedValueMissing" xml:space="preserve">
<value>The reference '{0}' used in the composed value at '{1}' resolved to no value.</value>
</data>
<data name="Error_ReferenceTemplateInvalid" xml:space="preserve">
<value>The composed value template at '{0}' is not a valid format string.</value>
</data>
@tarekgh

tarekgh commented Jul 16, 2026

Copy link
Copy Markdown
Member

@rosebyte could you please get some benchmarks reading configuration especially without references to ensure we don't have any perf regression with configuration reading. Thanks!

@rosebyte

Copy link
Copy Markdown
Member Author

@tarekgh, I'm doing it continuously when iterating the code, with the current approach we are about the same level in general with the only exception of complete miss (where we really have to check all parents down the road). I'm still simplifying the code and getting better results though.

Copilot AI review requested due to automatic review settings July 17, 2026 07:21
@rosebyte
rosebyte force-pushed the configuration-references branch from 89f57b0 to f0f5076 Compare July 17, 2026 07:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 11 out of 11 changed files in this pull request and generated 3 comments.

Comment thread src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx Outdated
Comment on lines +15 to +18
// A value is a reference when it carries the marker ref(target): the subject takes the target's value and mirrors
// its subtree. A leading backslash escapes the marker (\ref(...)) and yields the literal text with the backslash
// removed. Any other value is taken verbatim, and a direct non-empty value always wins over a value inherited
// through an ancestor reference.
Comment on lines +66 to +74
private void Promote(string key, CacheEntry entry)
{
// First writer wins: a key resolves to the same result for the life of this instance, so an existing entry
// is left untouched. Only a genuine insert counts toward the rotation threshold.
if (_hot.TryAdd(key, entry) && Interlocked.Increment(ref _hotCount) >= GenerationCapacity)
{
Rotate();
}
}

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

Comment on lines +188 to +204
private int _hops;
private HashSet<string>? _fired;

public void Advance(string key, int prefixLength)
{
if (++_hops <= GraceHops)
{
return;
}

string governing = key.Substring(0, prefixLength);
if (!(_fired ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase)).Add(governing))
{
throw new InvalidOperationException(
SR.Format(SR.Error_ReferenceCycle, string.Join(" -> ", _fired) + " -> " + governing));
}
}
Comment on lines +662 to +664
bool fired = false;
ChangeToken.OnChange(root.GetReloadToken, () => fired = true);

Copilot AI review requested due to automatic review settings July 22, 2026 05:05
@rosebyte
rosebyte force-pushed the configuration-references branch from b7e0b86 to 452f9f0 Compare July 22, 2026 05:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 1 comment.

Comment on lines +119 to +125
if (targets is null)
{
return Empty;
}

return new ReferenceIndex(Flatten(targets));
}
rosebyte added 2 commits July 23, 2026 08:51
Copilot AI review requested due to automatic review settings July 23, 2026 06:51
@rosebyte
rosebyte force-pushed the configuration-references branch from 452f9f0 to 129b0bf Compare July 23, 2026 06:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

Comments suppressed due to low confidence (1)

src/libraries/Microsoft.Extensions.Configuration/src/ReferenceEngine.cs:210

  • CycleGuard builds the exception message from a HashSet (string.Join over _fired), which is not ordered and can produce nondeterministic, hard-to-debug cycle strings. Since this is a user-facing error, it should be stable and ideally reflect the actual walk order.
                string governing = key.Substring(0, prefixLength);
                if (!(_fired ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase)).Add(governing))
                {
                    throw new InvalidOperationException(
                        SR.Format(SR.Error_ReferenceCycle, string.Join(" -> ", _fired) + " -> " + governing));
                }

Comment on lines +111 to +122
foreach (KeyValuePair<string, string?> entry in ScanProvider(provider))
{
// The highest provider that declares a path's $ref decides it; claim the path here so a lower
// provider's $ref for the same path is ignored. An empty target claims the path but records no
// reference, so a higher provider can drop a lower reference by setting its $ref to empty.
if (IsRefKey(entry.Key, out string? referencePath)
&& (claimed ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase)).Add(referencePath)
&& !string.IsNullOrEmpty(entry.Value))
{
(targets ??= new Dictionary<string, (string Target, int Level)>(StringComparer.OrdinalIgnoreCase))[referencePath] = (entry.Value!, i);
}
}
Comment on lines +32 to +35
// Exposes this provider's key/value pairs so the reference engine can build its reference index by scanning the
// already-loaded backing dictionary directly, instead of going through the O(n^2) GetChildKeys reconstruction.
internal IEnumerable<KeyValuePair<string, string?>> GetEntriesForReferenceScan() => Data;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants