Repository navigation
#89: share suffix and middle slices of long strings; hash long ASCII strings as bytes - #195
Conversation
Slices from an offset (copy-on-write, extends #186's prefix sharing): - BinaryContent and CharArrayContent get a start offset. A long slice from anywhere - s[n..], strip/lstrip, byteslice, delete_prefix, slice!'s result, split fields - shares the array from that offset, under the same rule as prefixes (at least 256 items and at least half of the array: Utils.IsSharedSlice). - The offset is non-zero only while the array is shared, and every write goes through EnterWrite, which copies the items to an array of their own at offset 0. Writes keep indexing the array directly; every read adds the offset (spans throughout). Removing from the start of a shared content moves the offset instead of copying, under the same retention rule. - GetByteArray hands out (array, start, count); the writers (RubyBufferedStream, Win32API buffers) get a normalized array through EnsureCapacity / GetWritableByteArray. TrimExcess and SetCapacity unshare first. - String#[] with a range/start-count and slice!'s result go through GetSlice instead of appending into a new string, and byteslice of a string held as bytes slices its content. Hash: - A string whose characters are all ASCII, in an encoding where ASCII characters are the same bytes both ways (not dummy), hashes its bytes: Marvin (String.GetHashCode's per-process seeded hash) over the bytes read two to a UTF-16 unit, the odd byte mixed in with HashCode. Half the bytes the UTF-16 hash read. Anything else hashes its characters as before. Empty strings hash alike in every encoding (all #eql?). - ClrString#hash uses the same function, as a CLR string is #eql? to a String of the same characters. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tHashCode A string under 128 items costs about the same either way, and narrowing it first made a Hash lookup with a short ASCII key a little slower. ASCII characters and bytes are as many, so the length test does not depend on how the string is held. SkipLocalsInit for the stack buffers; an even length needs no extra mixing step. 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 4 minutes. View limit details
|
GetByteSlice checked `_content is BinaryContent` and then sliced `_content`
again. A read on another thread can switch the string between bytes and
characters in between (index with a non-ASCII needle switches to characters,
getbyte back), and the byte offsets were then taken as character indices: on
a frozen ("é" * 1000) with three reader threads, byteslice(2, 600) returned
600 characters 186 times in 2.29M calls (0 on master). It now slices the
content it looked at: 0 in 2.5M.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClrString#eql? compares characters in any encoding, but a long ASCII String
in UTF-16/32 or a dummy encoding hashed its UTF-16 characters while the CLR
string hashed them narrowed: {("a"*200).encode("UTF-16LE") => 1}[clr] was
nil and [clr, s].uniq had two elements (one on master). Long ASCII
characters are now hashed narrowed in every encoding: decoded first where
the encoding's ASCII bytes are not its characters, straight from the bytes
where they are.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e rejects a negative start - HashCharacters and BinaryContent.CalculateHashCode no longer trust the cached ASCII flags: a write in place can leave a stale "not ASCII" behind, and the hash would then depend on how the string is held. Narrowing stops at the first non-ASCII character, and Ascii.IsValid is vectorized. - Stream.Write(MutableString, start, count): a negative start plus a slice's offset could name a byte before the slice; it throws, as Stream.Write did before the offset. - GetHashCode2 no longer asserts that two different seeded hashes differ. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
Dismissed because a newer commit was pushed; Greptile will re-review the current head.
| if (_content.IsOffsetSlice) { | ||
| // A slice from an offset is not written in place (see Content.IsOffsetSlice); its copy | ||
| // is a content of its own, so this also covers CopyOnWriteFlag. | ||
| _content = _content.Unslice(); |
There was a problem hiding this comment.
The first append to an offset slice now copies the whole string twice. Unslice() creates an array of exactly the current length. The append then outgrows that array, so Utils.Resize allocates another array and copies it again. This adds allocation and copying work to the targeted s.strip << "y" path for long strings.
Let the replacement reserve the space needed by the write, while still leaving the old content unchanged for readers.
Prompt To Fix With AI
This is a comment left during a code review.
Path: Src/Ruby/Builtins/MutableString.cs
Line: 526
Comment:
**Appending copies slices twice**
The first append to an offset slice now copies the whole string twice. `Unslice()` creates an array of exactly the current length. The append then outgrows that array, so `Utils.Resize` allocates another array and copies it again. This adds allocation and copying work to the targeted `s.strip << "y"` path for long strings.
Let the replacement reserve the space needed by the write, while still leaving the old content unchanged for readers.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Part of #89: the "
String#dup,+,stripandhashon ~100 KB strings" item. It builds on #186's copy-on-write content.What changes
1. Slices from an offset share the array (
strip,lstrip,s[n..],byteslice, ...)BinaryContentandCharArrayContentget a start offset (_start). A slice from anywhere in the string can now share the array, not only a prefix. The rule is the same one #186 used for prefixes, renamed fromIsSharedPrefixtoUtils.IsSharedSlice: at least 256 items, and at least half of the array (not of the string), so a small slice, or a slice of a slice, cannot keep a large array alive.How it stays sound:
_start != 0only on an offset slice, which is markedSharedand is never written (see below). So write code still indexes_datadirectly (_startis 0 there). Only reads add the offset, and reads now go throughGetDataSpan()and span helpers. The array-basedUtils.IndexOf/LastIndexOf/ValueCompareTooverloads became span overloads, so a missed call site does not compile.Content.IsOffsetSlice). Readers take no lock, and the array and the offset are two fields, so they must not change under a reader. The string replaces such a content with a copy at offset 0 (Unslice) before its first write. That happens inFrozenOrCopyOnWrite, which everyMutate*path takes, and inTrimExcess,Capacity,EnsureCapacityandGetWritableByteArray.EnterWriteSlowasserts that it never gets one.GetDataSpanreads the array once and never forms a span past it.Removeon a shared content: cutting the end keeps the array, as before. Anything else copies to offset 0 and unshares.GetByteArraynow returns(array, start, count)and its readers use the offset (MutableString.ToString(Encoding),IO#writeviaGetByteArrayChecked(ref start, …),Stream.Write(MutableString),RubyBufferedStream.EndsWith). The writers get an array that starts at 0:RubyBufferedStream's in-place backstop now usesGetWritableByteArrayafterEnsureCapacity, and Win32API buffers already did.TrimExcessandSetCapacityunshare first. Character enumerators carry the offset.GetSlice:String#[]/slicewith start/count or a range, andslice!'s returned part, used to append into a new string. They now callGetSlice.bytesliceof a string held as bytes slices its content (MutableString.GetByteSlice).strip/lstrip/split/delete_prefixalready usedGetSlice.2.
hashof long ASCII strings reads half the bytesA string of 128 items or more, all ASCII, in an encoding where ASCII characters are the same bytes both ways and that is not a dummy encoding (
RubyEncoding.AsciiRoundTrips), now hashes its bytes. It uses Marvin,String.GetHashCode's per-process seeded hash, over the bytes read two to a UTF-16 unit, and mixes an odd last byte in withHashCode.Combine, which is also seeded.Ascii.FromUtf16into a stack or pooled buffer).String.GetHashCodeof the characters. That covers short strings, non-ASCII, UTF-16/32 and dummy encodings, so short Hash keys cost what they did.eql?) hash alike.ClrString#hash(new[RubyMethod], initializers regenerated) uses the same function, because a CLR string iseql?to a String of the same characters.{System::String.new(k) => 1}[k]keeps working for long keys.3.
+: measured, not changedI tried building a long ASCII concatenation as bytes (half the size of the UTF-16 array). On net8.0
s + "x"went from 72 to ~40 µs. But a regexp on the result then has to switch it back to characters:(s + "x") =~ /y/went from 122 to 175–180 µs. So I dropped it.plus_x_bytes(bytes + bytes, onememcpy) costs about the same as the character case. The cost is the large-object-heap allocation and the gen-2 collections it brings on, not IronRuby code. WithDOTNET_GCLOHThreshold=0x200000,s + "x"takes ~10 µs (CRuby 8.75). That knob is process-wide policy, so it is left for a separate decision, as in #186. Measured alone and interleaved,+is unchanged by this PR: net10.0 56–75 µs on both builds, net8.0 57–68 on both. In the full suite run its number moves with what ran before it, because the GC's large-object budget adapts.Numbers
Release builds of
fork/master61bb889 and of this branch. Main-thread CPU (/proc/thread-self/stat),tasksetto one core, calibration pass as warm-up, best of 5 runs of at least 300 ms, interleaved master / branch / branch / master. CRuby 4.0.9 on a neighbouring core. Load average 3–5. µs per call;S = " " + "x" * 99_999(held as characters),SB= the same as bytes.S.strip(leading blank)S.lstripS[1..]SB.byteslice(1..)S.dup.slice!(0, 90_000)S.hashSB.hashS.strip.hashS.strip << "y"S.strip =~ /y/rstrip(shared since #186)S + "x"Small strings, same runs; no change beyond noise:
" hello world ".strip" hello world "[1..]"hello world\n".hash"日本語の文字列".hashBroad check:
Util/benchsuite(wall clock, so noisy) onmicro/string/,micro/hash/,liquid-cartandawfy/Json, master then branch. Every benchmark that moved was rerun interleaved (master / branch / branch / master):core-string-equal-10,-equal-1000000,gsub-*,inspect-*andliquid-cart-parse. In the rerun the branch falls inside master's own spread in each case. For exampleequal-10was 206/315 ns on master and 205/313 on the branch, andliquid-cart-parse1.1–1.2 ms on master and 0.94–1.16 ms on the branch. Nothing regressed.Verification
valid_encoding?) are identical to CRuby's.IO#readresult; aStringIO#readresult.[n..], middle slices, a slice of a slice, byteslice at the head, tail and middle, dup,+, interpolation,String.new, delete_prefix/suffix, aStringIOtail read,slice!and its result, a split field, a regexp slice, partition, each_line,unpack1("a*"),StringIO#gets.setbyteat the start, middle and end,[]=, insert/prepend, bytesplice,<< self, force_encoding,StringIO#write/truncate, and reads into the buffer:StringIO#read(n, buf)/readpartial,IO#read(n, buf),read(nil, buf),readpartial,sysread,pread, piperead.MutableString_CopyOnWrite5: readers of slices while they are written. 0 wrong reads, 0 errors.MutableString_CopyOnWrite3now also takesGetSlice(1, …)and prefix slices while another thread writes: 0 changed copies.s[1..],strip,byteslice(3..),[2, 3000],dupagainstsetbyte/insert-remove/append-trim/lstrip!writers, for chars, bytes and UTF-8 bytes) took ~800k copies: 0 changed, on master and on the branch.eql?⇒ samehash: every pair of 10 sample strings (empty, short, 300-char, non-ASCII, invalid) × everyEncoding.listentry × 6 ways to hold them (force_encoding,.b,encode, switched to characters, a slice from an offset): 789,635eql?pairs, 0 hash mismatches. Before the empty-string fix there were 44,362.MutableString_CopyOnWrite1: 5 more ways to copy (offset slices, slice of slice,GetByteSlice,Trim) and 2 more writes (an in-place read of the array,Capacity).CopyOnWrite2: 7 offset copies and 8 more mutators, including IO reads into the buffer; 7,056 checks, the count from CRuby.CopyOnWrite3: slices under concurrent writes.GetHashCode2: lengths around 128, offsets, US-ASCII/BINARY.GetHashCode3: Ruby level, including CLR string keys.String.try_convert"into"/"to" wording, on master too); library/stringio 682, 0/0; core/symbol 270, 0/0; core/io read/readpartial/sysread/pread/write/syswrite/read_nonblock/gets/binread 309, 0/0. The lists of failing examples are the same.Review
I ran the repo's
reviewskill (an independent pass, with repros). Both findings are confirmed and fixed in their own commits:bytesliceread_contenttwice. A read on another thread can switch a frozen string between bytes and characters (indexwith a non-ASCII needle switches to characters,getbyteswitches back). In between, byte offsets were taken as character indices. Repro: 3 reader threads on("é" * 1000).freeze. The wrong result came back 186 times in 2.29M calls on the branch and 0 on master; after the fix, 0 in 2.5M.String#[]has a similar check-then-slice race, but it was already on master and is worse there.eql?to a String of the same characters in any encoding. But a long ASCII String in UTF-16/32 or a dummy encoding hashed its UTF-16 characters while the CLR string hashed them narrowed:[clr, ("a"*200).encode("UTF-16LE")].uniq.sizewas 2 (1 on master). Long ASCII characters are now hashed narrowed in every encoding: decoded first where the encoding's ASCII bytes are not its characters, straight from the bytes where they are.GetHashCode3covers it.MutableString.Equals(string)is true for an equal CLR string, but for a long ASCII stringMutableString.GetHashCode()no longer equalsstring.GetHashCode(). A C# host that mixes the two as keys of one .NET dictionary would see that. The review could not reach it from Ruby, because the binder converts toSystem.Stringat CLR boundaries. The doc comment says so.Greptile (on 59c143b):
Stream.Write(MutableString, start, count)now rejects a negative start, which an offset could otherwise have turned into a byte before the slice.A second independent review (on f116a7e) found a torn read, fixed in df2678d:
s = base[1..]published to a reader and thens << "x",byteslice(0, 4)returned the parent's bytes a few hundred times in 8 s and raised RangeError ~200 times. Master: 0 and 0.MutableString_CopyOnWrite5reproduces it in C#. With offset slices written in place again, it reports 150–1140 wrong reads.S.strip << "y"is back at master's figure, whilestrip,[n..]andbyteslicethemselves stay O(1).MutateOne(char)writing an ASCII char into a string known not to be ASCII now makes its ASCII-ness unknown.After the fixes, all re-run on the final head:
eql?/hashover all encodings: 0 mismatches;What to scrutinize
_start != 0⇒Shared", and that nothing clearsSharedwithout resetting_start. OnlyEnterWriteSlowandUtils.RemoveShared's copying branch clear it._datathat still assumes offset 0.grep -n _datain the two content classes: what is left without_startis either insideEnterWrite/ExitWriteor the constructors.IsSharedSlicecompares against the array length. A shared slice now also keeps the bytes before it alive, which a prefix slice never did. It is still bounded by "at least half of the array".AsciiRoundTripspredicate (identity and not dummy) and the 128 threshold have to agree betweenBinaryContent.CalculateHashCodeandContent.HashCharacters. Hash values of long ASCII strings change, and long ASCIIMutableStrings no longer equalSystem.String.GetHashCode; the doc comment is updated.String#[]andslice!now return aGetSliceresult instead of an appended copy. The encoding and ASCII flags come fromGetSlice.🤖 Generated with Claude Code