Repository navigation
#89: copy-on-write strings (dup/clone/String.new/StringIO#read), hash without copying, faster ASCII literals - #186
Conversation
#dup, #clone, String.new(str), +@, #replace, #initialize_copy, an interpolation of a single string and StringIO#read of the whole buffer no longer copy the bytes or characters: BinaryContent and CharArrayContent share their array with the copy, both are marked shared, and each copies the array the first time it writes to it. A long prefix slice (at least 256 items and half the array) shares too, and cutting off the end of a shared array keeps it shared. Every write in the two content classes unshares first, with room for what the write appends, so a dup followed by an append still copies once. Callers outside them that write into the raw byte array (RubyBufferedStream via EnsureCapacity, Win32API via GetWritableByteArray) unshare too. String#hash no longer decodes a byte-held string into a new CLR string (it decodes into a pooled buffer), and a char-held one hashes its span. Exact-size copies (concatenation, slices, unsharing) allocate without zeroing first. Part of #89. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The compiler checks once whether a literal is all ASCII in an ASCII-compatible encoding; such a literal is created by a constructor that sets the content, encoding and character flags directly instead of working them out on every evaluation, and knows it is ASCII, so the first #bytesize, #hash or comparison does not scan it. Part of #89. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Next included review available in 19 minutes. View limit details
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
…ests do Co-Authored-By: Claude Opus 5.5 <[email protected]>
…via the array overload A slice of a slice compared its length with the string's rather than with the array it shares, so halving repeatedly could leave a 256-character string holding a large array; the guard now uses the array's length. EscapingEncoding implements only the array overloads, so the span GetChars used by String#hash for non-ASCII bytes went through temporary arrays; it now decodes into the pooled array directly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e original Review finding on #186: `_shared` was a plain bool, and there is no GVL. A writer could check that its array was its own, then a Clone on another thread set `_shared` and handed out that array, and the write landed in the copy. Worse, UnshareSlow could store its new array, a Clone could share it and mark it shared, and UnshareSlow then cleared the mark: every later write to the original went into the copy. A frozen dup (a Hash key) could change after it was returned. Reproduced: one thread loops s.setbyte(100, ...) (or insert/slice!) on a 4 KB string while the main thread dups it, reads, spins, and reads again. Before: 127-493 changed copies per 200k dups for setbyte, 2731 for insert/slice!. After: 0 in every run. BinaryContent and CharArrayContent replace the bool with a state word (ContentState): bit 0 says the array may be shared, bit 1 that a thread holds the content. Every write holds it between EnterWrite and ExitWrite, and Clone and the sharing GetSlice hold it while they read the array and count. The common write (unshared, not held) is one compare-exchange, and ExitWrite is a plain release store. An exception inside a write still releases it (try/finally). Cost, Release net8.0, best of interleaved runs, ns per op: setbyte 60 -> 61, setbyte on chars 51 -> 52, << 111 -> 106, insert 242 -> 246, slice! 270 -> 280, dup small 148 -> 149, dup 100 KB 152 -> 150. A plain `lock` was 18-35 % slower on setbyte and <<. MutableString_CopyOnWrite3 runs the race for bytes and characters, for a write in place and one that moves the tail; on the previous head it reports hundreds to thousands of changed copies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dismissed because a newer commit was pushed; Greptile will re-review the current head.
|
1d3e219 fixes a copy-on-write race that a review found. The race:
The fix:
Reproducer: one thread loops
The new Cost: Release net8.0, best of interleaved runs, ns per operation.
A plain Checked:
|
Greptile P1 on #186 (1d3e219): Append(Stream, int) called stream.Read while it held the content for the write. Holding is not reentrant, so a stream whose Read copies the string it is read into waited for itself forever. A blocking pipe or socket read also made every #dup of that string on another thread spin until the read returned. The read now goes into a pooled buffer first, and the bytes are appended with the ordinary held Append(byte[]). I checked the other held sections: they run only array copies and IronRuby's own encoders, with no stream, no user code and nothing that reaches the same string. ContentState's comment now states that rule. MutableString_CopyOnWrite4 appends from one stream whose Read clones the destination, and from one whose Read waits for a clone on another thread, for byte and character strings. On 1d3e219 it reports "Append(Stream) hung"; now it passes on net8.0 and net10.0. Checked: the race reproducer still gives 0 changed copies; core/string (only the known try_convert wording error), library/stringio and core/io read* are unchanged; full IronRuby.Tests on net8.0 passes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
def3ed6 fixes Greptile's P1 "Custom stream reads can hang". The fix: The rest of the held sections: I checked them all. They run only array copies and IronRuby's own encoders. None reads a stream, runs user code, or calls back into the same string, so none needs to be reentrant. New test:
On 1d3e219 it reports "Append(Stream) hung"; now it passes on net8.0 and net10.0. Checked:
|
…the array read Readers take no lock, and an offset slice's first write replaced its array and its offset - two fields - in place, so a reader on another thread could pair the new array with the old offset (or the reverse) and read bytes from outside the string: with `s = base[1..]` published to a reader and then `s << "x"`, byteslice(0, 4) gave the parent's bytes a few hundred times in 8 seconds and raised RangeError a couple of hundred times (0 on master). - A content that is a slice from an offset (Content.IsOffsetSlice) now never changes. The string replaces it with a copy at offset 0 (Unslice) before its first write: in FrozenOrCopyOnWrite, which every Mutate* path takes, and in TrimExcess, Capacity, EnsureCapacity and GetWritableByteArray. EnterWriteSlow asserts that it is not handed one. - Removing from the start of a shared content no longer moves the offset in place; it copies, as #186 did. - GetDataSpan reads the array once and never forms a span past it, so a prefix slice growing on another thread (array and count replaced separately) is not a RangeError either. - MutateOne(char): an ASCII char written into a string known not to be ASCII makes its ASCII-ness unknown, as MutateOne(byte) does. - MutableString_CopyOnWrite5: readers of suffix and prefix slices, bytes and characters, while the slices are written: 0 wrong reads, 0 errors. With the offset slice written in place again it reports 150-1140 wrong reads. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Part of #89. Two of its unticked Strings items, one commit each.
#89 items this addresses
String#dup,+,stripandhashon ~100 KB strings are 10× or more slower than CRuby;StringIO#readof the whole buffer has the same cause. Copies now share the buffer (copy-on-write).dup/clone/String.new/whole-bufferStringIO#readare now constant time.hashno longer copies.+andstripmust build a new string; they make one copy each, and what is left of their cost is the .NET GC (see below)."hello world\n".bytesize(~2× faster). Two allocations per literal remain (see below).All numbers: Release net8.0 builds of
fork/master(31e508c) and of this branch, main-thread CPU (/proc/thread-self/stat), pinned withtaskset, interleaved master / branch / branch / master, best of 5 rounds of at least 300 ms each, with a warm-up pass first. CRuby is 4.0.9 on the same core. The box was heavily loaded (load average around 30 on 8 cores), so treat differences under ~10 % as noise.1. Copy-on-write content (7df1d5f)
BinaryContentandCharArrayContentget a_sharedflag.Content.Clone()no longer copies the array. It sets_sharedon both contents and hands the same array to the copy. Every method in the two classes that writes into the array callsUnshare(minCapacity)first. That covers Append*, Insert*, SetByte/SetChar/DataSetChar, Remove, Write, and theCountsetter.Unsharecopies the array once, with room for what the write is about to add, sos.dup << "x"still copies only once.Removeon a shared array copies only what is left. If it only cuts off the end, it just shortens the view and keeps the array shared.The content object stays the same; only its array changes. So code holding the content (
Reverse, theCopyOnWriteFlagthat enumerators use) works unchanged.StringContentis an immutable CLR string, so it needs nothing.What now shares:
Content.Clone()users:#dup/#clone(initialize_copynow calls the newMutableString.Replace(other)),String#replace,String.new(str),+@,"#{str}",CloneDerived,CreateFrozenSnapshotfor byte content, and the existingCopyOnWriteFlag(enumeration) path.StringIO#read/read(nil, buf)/read(n)when the read covers the whole string from position 0.GetSliceprefixes of at least 256 items that keep at least half of the array (its length, not the string's, so a slice of a slice cannot keep a big array alive) (s[0, n],byteslice(0, n),chomp,rstrip). Short slices are still copied, so a small slice cannot keep a large array alive.Raw-array writers outside the classes:
RubyBufferedStreamwrites intoGetByteArrayafterEnsureCapacity.EnsureCapacitynow unshares.RubyOps.GetMutableStringBytes(Win32API buffers that native code fills) now uses the newGetWritableByteArray.GetByteArray/GetDataSpan/GetCharacterDatauser (grep): all of them only read. Only the Ruby assembly can reach the content classes.Thread safety is no worse than before. A reader only ever sets
_sharedto true, and only on the content it copies. A concurrent reader can at worst cause one unnecessary copy. A write racing with adupof the same string was already a data race, and before it could produce a torn copy. A string handed to another thread afterdupis safe: the shared array is never written again, because each side writes into a copy of its own.Hash:
BinaryContent.CalculateHashCodedecoded the bytes into a new CLR string on every call, a large-object-heap allocation for a long string. It now decodes into a stack orArrayPoolbuffer and usesString.GetHashCode(ReadOnlySpan<char>), which .NET defines to equalstring.GetHashCode().CharArrayContenthashes its span directly. The hash value is unchanged (MutableString_GetHashCode2).Exact-size copies: concatenation,
GetSlice, and the copy inUnsharenow allocate withGC.AllocateUninitializedArray. These copies overwrite every item, and zeroing a large array cost about as much as the copy itself. Spare room past the end is still cleared.s.dups.b.dup(bytes)s.cloneString.new(s)StringIO#read(whole, 650 KB)s.dup << "x"s + "x"s.strip(leading blank)s.hashWhat is left, measured, not changed:
+,stripanddup <<still need one copy of a 100 KB string. Held as UTF-16, that is a 200 KB array on the large object heap. Aperfprofile ofs + "x"puts ~26 % in the GC's background mark/sweep and a few % in kernel page faults, against ~6 % inmemcpy: every few such allocations trigger a gen-2 collection. WithDOTNET_GCLOHThreshold=0x100000(only for the experiment, not changed here),+went 65→45 µs anddup <<80→35 µs in the same run. WithDOTNET_gcConcurrent=0they go to ~450 µs, because the gen-2 GCs then run on the main thread. So the remaining gap is GC policy and the 2-byte character representation, not IronRuby code. RaisingSystem.GC.LOHThresholdfor the whole runtime would be a separate decision with process-wide effects, so it is left as a lever for later.stripwith a leading blank needs a slice that does not start at 0. Sharing those would need an offset in the content classes, which touches every array index in them, so it is not done here.rstripandchompnow share.hashno longer allocates. Its cost is Marvin over 2 bytes per character (~200 KB), against CRuby's SipHash over 100 KB. Using a different hash function would break the documented equality withSystem.String.GetHashCode.2. ASCII literals (124b41a)
When a literal is all ASCII in an ASCII-compatible encoding, which the compiler checks once, it now compiles to
RubyOps.CreateChilledMutableStringAorCreateMutableStringA. These set the content, encoding and flags (IsAscii,NoSurrogates, and the chilled bit) directly, instead ofSetEncoding/SetContentworking them out on every evaluation. The string also knows it is ASCII, so its firstbytesize,hashor comparison does not scan it. The chilled-literal warning is unchanged.x = "hello world""hello world\n".bytesize"hello world\n".hashThe IronRuby loop itself costs ~2 ns. A
perfprofile of the branch shows the rest: the two allocations per literal (MutableString+StringContent, ~14 % in the allocation helper plus__tls_get_addr), four GC write barriers (~7 %), and the inlined constructor. Removing theStringContentallocation would need content objects that do not point back to their owner. Content code uses that back-pointer everywhere, including to switch representation, so this PR does not do it.Tests
MutableString_CopyOnWrite1covers 4 representations (bytes ASCII/UTF-8, chars with/without non-ASCII), 7 ways of copying and 42 kinds of write through theMutableStringAPI, including the raw-array paths ofRubyBufferedStreamand Win32API and a write during enumeration. Each write is done on the copy and on the original. The other string must not change, and the written one must match an unshared string given the same write.MutableString_CopyOnWrite2is the same at the Ruby level: 4 strings × 14 ways to copy (dup,clone,String.new,+@,replace,initialize, threeStringIO#readforms,bytesliceprefix,chomp,[0, length], subclassto_s, interpolation) × 34 mutating String/StringIO methods × both directions, for 3808 checks. CRuby 4.0.9 gives the same output.MutableString_GetHashCode2: hashes agree across bytes, chars, CLR strings and copies, for short strings (stack buffer) and long ones (pooled buffer).Unsharecalls removed, the Ruby-level check reports 221 failures.Verification
String.try_convert's "into"/"to" wording and is on master too. library/stringio 682 examples, core/symbol 270 and core/io/read* 233, all clean. language 2935 examples, 1 error, the same wording one as on master. None of these is new against master (31e508c).Util/parallel-sweep.sh, branch (rebased on 80419b0) against a master baseline (31e508c):Timeout.timeout raises specified error type when it times out. It is a load flake (the box was at load ~30): spec/library/timeout passes 7/7 on a re-run.-Sexamples, from Issue #89 leftovers: EUC-KR table gaps, #92 regression tests, cheaper Thread.new location #184).MutableString_CopyOnWrite2, whose first version did not load the prelude (fixed in e655f57). The new tests pass on both TFMs at the final head.hashwent throughEncoding's span overload, whichEscapingEncodingdoes not implement, so it allocated temporary arrays; it now decodes into the pooled array. CodeRabbit was rate-limited on this PR and has not reviewed it. My own pass over every write path found nothing else.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Performance


Confidence Score: 5/5
The PR appears safe to merge; the earlier stream-read hang is fixed and no new actionable issues were found.Summary
This PR lets string copies share their storage until either string changes. It also avoids copies during hashing and speeds up ASCII literals.
Reviews (5) · Last reviewed commit: "Append(Stream): read before holding the ..." · Reviewed by Greptile