Repository navigation
fix!: thread-safety and mutability fixes for IPNetwork2 and collections (5.0.0) - #459
Merged
Merged
Conversation
TDD red phase for four defects found while auditing the surroundings of #429. These tests fail on purpose: no production code is changed here, so this branch must not be merged or pushed to CI as it stands. IPNetworkCollection implements IEnumerable and IEnumerator at once and returns this from GetEnumerator, so every consumer shares one cursor: second foreach over the same collection -> 0 elements instead of 4 nested foreach over the same collection -> 3 pairs instead of 16 two concurrent foreach -> ArgumentOutOfRangeException The first two need no concurrency at all. The concurrent case is worse than losing elements: one thread can advance the cursor past Count while another calls Current, which indexes out of range and throws. IPAddressCollection already hands out a dedicated enumerator instance, so the pattern to follow is in the codebase. The Value setter rewrites ipaddress, family and cidr as three separate unsynchronized writes, so a reader can pair the new CIDR with the old address and observe 10.0.0.0/24, a network that was never assigned. GetHashCode is memoized in a readonly Lazy built in the constructor and never invalidated by the Value setter, so a mutated instance keeps the hash of its former value. Equal instances then carry different hash codes and HashSet.Contains misses them, which breaks the Equals/GetHashCode contract. The existing deserialization tests do not catch this because the setter runs before the Lazy is ever materialized. The IANA blocks are process wide singletons whose Value setter is public, so any caller can rewrite them and change what the library reports as reserved. The test restores the singleton in a finally, and the rest of the suite stays green: 1371 total, 7 failed, 1364 passed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Second sweep of the concurrency audit. Still red on purpose, still no
production code changed.
Both indexers guard only the upper bound:
if (i >= this.Count) throw new ArgumentOutOfRangeException(nameof(i));
Nothing rejects a negative index, so it resolves to an element located
before the network and is returned silently:
subnets[-1] -> 192.168.0.192/26 (parent 192.168.1.0/24)
ListIPAddress()[-1] -> 192.168.0.255
This is reachable without ever computing an index, because the cursor of
both collections starts at -1. Reading Current before the first
MoveNext() returns the out of range element, and a Reset() issued by
another thread mid-enumeration does the same: reproduced after a single
read, yielding 192.168.0.255/32 from a 192.168.1.0/24 enumeration.
Handing back an address outside the range instead of throwing is the
dangerous failure mode for a library used to decide whether an address
belongs to a network.
Also adds a deterministic guard on IPNetworkCollection.GetEnumerator()
returning an instance distinct from the collection. It covers the shared
cursor and its side effect: since the collection is its own enumerator,
it is also the IDisposable that foreach disposes at the end of every
loop. Harmless today because Dispose is a no-op, but it disappears once
the enumerator is separated, the way IPAddressCollection already does.
Suite: 1376 total, 12 failed, 1364 passed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
IPNetworkCollection implemented IEnumerable and IEnumerator at once and returned this from GetEnumerator, so every consumer shared the single cursor held in a field of the collection. Without any concurrency involved, a second foreach over the same collection yielded 0 elements instead of 4, and a nested foreach visited 3 pairs instead of 16, because the inner loop consumed the cursor of the outer one. Concurrently, two enumerations of a 256 element collection returned 258 elements between them instead of 512, and depending on the interleaving one thread could advance the cursor past Count while another called Current, which indexes out of range and throws. GetEnumerator now returns a private Enumerator struct carrying its own cursor, exactly as IPAddressCollection already does. The public IEnumerator members of the collection are kept so the change is not breaking; they are legacy surface that no longer takes part in foreach. This also removes a side effect of the collection being its own enumerator: foreach disposes the enumerator when it ends, which meant disposing the collection itself on every loop. Harmless while Dispose is a no-op, gone now. Tests: the four red tests turn green, including the structural guard that GetEnumerator must not return the collection. Ran the group 10 times in a row to confirm the concurrent one does not flake. Suite goes from 12 to 8 failures, the remaining 8 being the defects not addressed here: the unchecked negative index in both indexers, the non-atomic Value setter, the stale hash code and the rewritable IANA singletons. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Both indexers guarded only the upper bound:
if (i >= this.Count) throw new ArgumentOutOfRangeException(nameof(i));
Nothing rejected a negative index, so it resolved to an element located
before the network and was returned silently:
subnets[-1] -> 192.168.0.192/26 (parent 192.168.1.0/24)
ListIPAddress()[-1] -> 192.168.0.255
This was reachable without ever computing an index, because the cursor
of both collections starts at -1. Reading Current before the first
MoveNext returned the out of range element, and a Reset issued by
another thread mid-enumeration did the same, reproduced after a single
read. For a library used to decide whether an address belongs to a
range, handing back an element outside that range instead of throwing is
the dangerous failure mode.
The guard now covers both bounds, and the exception documentation says
so.
BEHAVIOUR CHANGE, worth a note in the release notes: reading Current
before the first MoveNext, or after Reset, now throws
ArgumentOutOfRangeException instead of returning an element outside the
network. The BCL treats Current in that state as undefined and its
collections throw, so this aligns with the platform, but code relying on
the old return value will now see an exception.
Six existing tests asserted the old behaviour and were updated, since
each of them read Current with the cursor at -1:
TestEnumeratorCurrent, TestEnumeratorCurrentOor,
Test_ipv6_EnumeratorCurrent, Test_ipv6_EnumeratorCurrentOor
Assert.IsNotNull(ips.Current) before the first MoveNext, now
asserting the throw.
TestIterateIPAddress
read Current through the collection after a foreach; since foreach
now uses a separate enumerator the collection cursor is still at -1.
TestReset1
compared two out of bounds reads of Current, which never exercised
Reset. It now moves, reads, resets, moves and reads again, so it
actually tests that Reset returns to the first element.
Suite: 1376 total, 4 failed, 1372 passed. The 4 remaining failures are
the defects not addressed here: the non-atomic Value setter, the stale
hash code and the rewritable IANA singletons.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…tons Hold the address, family and CIDR in one immutable Snapshot behind a single volatile reference, so the Value setter replaces the whole network in one store and every reader sees a network that was actually assigned. The broadcast and hash caches live on the snapshot and are dropped with it, so they can no longer go stale. The IANA_* blocks and the ULA prefixes now hand out a copy sharing the immutable snapshot, so callers can no longer rewrite them for the whole process. Bump the version to 5.0.0 (AssemblyVersion 5.0.0.0). BREAKING CHANGE: GetHashCode now follows Value, as the Equals/GetHashCode contract requires; a network mutated after being added to a dictionary or a set can no longer be found there. UniqueLocalAddress.UlaLocallyAssigned, UlaCentrallyAssigned and UlaRange are now properties instead of static readonly fields, which breaks binary compatibility. The IANA_* properties and the ULA properties return a new instance on every call, so reference equality between two calls no longer holds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
lduchosal
had a problem deploying
to
github-pages
October 24, 2026 14:07 — with
GitHub Actions
Failure
Contributor
|
This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again. |
Coverage Report for CI Build 1047Coverage increased (+0.1%) to 94.172%Details
Uncovered ChangesNo uncovered changes found. Coverage RegressionsNo coverage regressions found. Coverage Stats
💛 - Coveralls |
…, IDE0017) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
lduchosal
had a problem deploying
to
github-pages
October 24, 2026 14:17 — with
GitHub Actions
Failure
Cover every IANA_* property now that IsIANAReserved no longer goes through them, and the Reset of the new collection enumerator. Drop the now unused InternalNetmask, and the zero-hash branch that no test could reach: a network hashing to zero is simply recomputed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
lduchosal
had a problem deploying
to
github-pages
October 24, 2026 14:44 — with
GitHub Actions
Failure
|
This branch had an error being deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Summary
Fixes the thread-safety and mutability defects found during the audit. Each defect is first reproduced by a red test, then fixed.
IPNetwork2
Snapshotbehind a singlevolatilereference. TheValuesetter replaces the whole network in one store, so a concurrent reader can no longer observe a network that was never assigned (new CIDR paired with the old address, for example).Valueinvalidates them. Before, the hash was frozen in aLazyand went stale.ToString,Contains,CompareTo,Network,Broadcast,FirstUsable,LastUsable,Usable,WildcardMask, ...) reads the snapshot once per call.IANA_*blocks and the ULA prefixes now return a copy that shares the immutable snapshot, so a caller can no longer rewrite them for the whole process.Collections
IPNetworkCollectiongets an enumerator of its own instead of a cursor shared by every enumeration.IPNetworkCollectionandIPAddressCollectionreject negative indexes.Version
The version goes to 5.0.0:
PackageVersion,VersionandAssemblyVersion/AssemblyFileVersion(which were still at 3.2.0.0).appveyor.ymlgoes to5.0.{build}.Breaking changes
GetHashCodenow followsValue, as theEquals/GetHashCodecontract requires. A network mutated after being added to a dictionary or a set can no longer be found there.GetHashCodeUnitTestis updated to match.UniqueLocalAddress.UlaLocallyAssigned,UlaCentrallyAssignedandUlaRangeare now properties instead ofstatic readonlyfields. Code compiled against the old version must be recompiled.IANA_*and ULA properties return a new instance on every call, soReferenceEqualsbetween two calls no longer holds.Tests
dotnet src/TestProject/bin/Debug/net10.0/TestProject.dll).After merge
Create the release with the tag
5.0.0.release.ymltakes the published version from the tag.🤖 Generated with Claude Code