Skip to content

#89: share suffix and middle slices of long strings; hash long ASCII strings as bytes - #195

Merged
Largo merged 6 commits into
masterfrom
claude/issue-89-string-slices
Nov 10, 2026
Merged

Largo merged 6 commits into
masterfrom
claude/issue-89-string-slices

Conversation

@Largo

@Largo Largo commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Part of #89: the "String#dup, +, strip and hash on ~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, ...)

BinaryContent and CharArrayContent get 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 from IsSharedPrefix to Utils.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:

  • Invariant: _start != 0 only on an offset slice, which is marked Shared and is never written (see below). So write code still indexes _data directly (_start is 0 there). Only reads add the offset, and reads now go through GetDataSpan() and span helpers. The array-based Utils.IndexOf/LastIndexOf/ValueCompareTo overloads became span overloads, so a missed call site does not compile.
  • An offset slice never changes (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 in FrozenOrCopyOnWrite, which every Mutate* path takes, and in TrimExcess, Capacity, EnsureCapacity and GetWritableByteArray. EnterWriteSlow asserts that it never gets one. GetDataSpan reads the array once and never forms a span past it.
  • Remove on a shared content: cutting the end keeps the array, as before. Anything else copies to offset 0 and unshares.
  • Raw arrays: GetByteArray now returns (array, start, count) and its readers use the offset (MutableString.ToString(Encoding), IO#write via GetByteArrayChecked(ref start, …), Stream.Write(MutableString), RubyBufferedStream.EndsWith). The writers get an array that starts at 0: RubyBufferedStream's in-place backstop now uses GetWritableByteArray after EnsureCapacity, and Win32API buffers already did. TrimExcess and SetCapacity unshare first. Character enumerators carry the offset.
  • Callers switched to GetSlice:
    • String#[]/slice with start/count or a range, and slice!'s returned part, used to append into a new string. They now call GetSlice.
    • byteslice of a string held as bytes slices its content (MutableString.GetByteSlice).
    • strip/lstrip/split/delete_prefix already used GetSlice.

2. hash of long ASCII strings reads half the bytes

A 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 with HashCode.Combine, which is also seeded.

  • Strings held as characters narrow first (Ascii.FromUtf16 into a stack or pooled buffer).
  • Everything else keeps the old hash, String.GetHashCode of the characters. That covers short strings, non-ASCII, UTF-16/32 and dummy encodings, so short Hash keys cost what they did.
  • Consistency:
    • ASCII characters and bytes are as many, so the length test does not depend on how the string is held.
    • Equal ASCII strings in US-ASCII/UTF-8/BINARY (all eql?) hash alike.
    • Empty strings hash alike in every encoding.
    • ClrString#hash (new [RubyMethod], initializers regenerated) uses the same function, because a CLR string is eql? to a String of the same characters. {System::String.new(k) => 1}[k] keeps working for long keys.
  • Hash flooding: both hashes stay seeded per process. An even-length ASCII string hashes as the UTF-16 string its bytes spell, which is not ASCII. That gives collision pairs that do not depend on the seed, but never more than pairs. This is noted in the code.

3. +: measured, not changed

I 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, one memcpy) 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. With DOTNET_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/master 61bb889 and of this branch. Main-thread CPU (/proc/thread-self/stat), taskset to 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.

100 KB string net8.0 master net8.0 branch net10.0 master net10.0 branch CRuby
S.strip (leading blank) 59–60 0.58–0.64 54–55 0.88–0.91 0.14
S.lstrip 69–70 0.49 62 0.50–0.53 0.13
S[1..] 58 0.19–0.40 54–56 0.17–0.31 0.15
SB.byteslice(1..) 68–70 0.20–0.36 50–61 0.22–0.23 0.13
S.dup.slice!(0, 90_000) 54–59 3.1–3.6 44–49 2.5–2.9 16
S.hash 75 45 75–80 45 24
SB.hash 82–85 40–41 82–92 41–44 24
S.strip.hash 112–120 45 110–115 44–45 24
S.strip << "y" 160–180 150–155 (59 before df2678d) 102–140 132–135 (50 before) 69
S.strip =~ /y/ 122–125 61–64 95–110 54 30
rstrip (shared since #186) 0.33–0.41 0.41–0.53 0.33–0.40 0.31–0.40 7.5 (copies)
S + "x" see above 8.75

Small strings, same runs; no change beyond noise:

net8.0 master net8.0 branch net10.0 master net10.0 branch CRuby
" hello world ".strip 0.38–0.39 0.40–0.41 0.32–0.49 0.35–0.46 0.14
" hello world "[1..] 0.22–0.26 0.23–0.24 0.19–0.29 0.20 0.14
"hello world\n".hash 0.15–0.17 0.17–0.20 0.14–0.19 0.16–0.17 0.10
100 Hash lookups, 12-char keys 7.0 6.75 6.0–7.0 6.5–10 8.0
"日本語の文字列".hash 0.15–0.17 0.16–0.18 0.14–0.17 0.14–0.17 0.12

Broad check: Util/benchsuite (wall clock, so noisy) on micro/string/, micro/hash/, liquid-cart and awfy/Json, master then branch. Every benchmark that moved was rerun interleaved (master / branch / branch / master): core-string-equal-10, -equal-1000000, gsub-*, inspect-* and liquid-cart-parse. In the rerun the branch falls inside master's own spread in each case. For example equal-10 was 206/315 ns on master and 205/313 on the branch, and liquid-cart-parse 1.1–1.2 ms on master and 0.94–1.16 ms on the branch. Nothing regressed.

Verification

  • Mutation matrix vs CRuby 4.0.9: 30,132 checks, and the per-check digests (size, CRC32, encoding, valid_encoding?) are identical to CRuby's.
    • 9 sources: ASCII as characters, as bytes and as UTF-8 bytes; BINARY with a high byte; UTF-8 as characters and as bytes; UTF-16LE; an IO#read result; a StringIO#read result.
    • 31 ways to copy: strip/lstrip/rstrip/chomp, [n..], middle slices, a slice of a slice, byteslice at the head, tail and middle, dup, +, interpolation, String.new, delete_prefix/suffix, a StringIO tail read, slice! and its result, a split field, a regexp slice, partition, each_line, unpack1("a*"), StringIO#gets.
    • 54 mutators, each applied to the copy and to the original: every String bang method, setbyte at 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, pipe read.
    • Run on the Debug build, so assertions were on.
    • To check that the matrix exercises the offset, I broke the sharing (a slice from an offset not marked shared). It then reported failures and an out-of-range read.
  • Concurrency:
    • MutableString_CopyOnWrite5: readers of slices while they are written. 0 wrong reads, 0 errors.
    • MutableString_CopyOnWrite3 now also takes GetSlice(1, …) and prefix slices while another thread writes: 0 changed copies.
    • A Ruby stress test (s[1..], strip, byteslice(3..), [2, 3000], dup against setbyte/insert-remove/append-trim/lstrip! writers, for chars, bytes and UTF-8 bytes) took ~800k copies: 0 changed, on master and on the branch.
    • Reads racing a writer on the same string still raise now and then, at the same rate as on master (no GVL; this was already so).
  • eql? ⇒ same hash: every pair of 10 sample strings (empty, short, 300-char, non-ASCII, invalid) × every Encoding.list entry × 6 ways to hold them (force_encoding, .b, encode, switched to characters, a slice from an offset): 789,635 eql? pairs, 0 hash mismatches. Before the empty-string fix there were 44,362.
  • IronRuby.Tests (Debug, net8.0): full suite PASSED, 0 failures. New or extended:
    • 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.
    • New GetHashCode3: Ruby level, including CLR string keys.
  • ruby/spec at CI's refs (SPEC_REF dda28d04), Release, master vs branch: identical on both builds: core/string 3963 examples, 0 failures, 1 error (the known 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 review skill (an independent pass, with repros). Both findings are confirmed and fixed in their own commits:

  • Blocker, fixed in 0cf70a5: byteslice read _content twice. A read on another thread can switch a frozen string between bytes and characters (index with a non-ASCII needle switches to characters, getbyte switches 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.
  • Should fix, fixed in f116a7e: a CLR string is 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.size was 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. GetHashCode3 covers it.
  • Note, not changed: MutableString.Equals(string) is true for an equal CLR string, but for a long ASCII string MutableString.GetHashCode() no longer equals string.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 to System.String at CLR boundaries. The doc comment says so.

Greptile (on 59c143b):

  • It found the same CLR/UTF-16 hash issue (already fixed).
  • It found that the hash trusted cached "not ASCII" flags, which a write in place can leave stale. The hash now checks the characters and bytes themselves.
  • Stream.Write(MutableString, start, count) now rejects a negative start, which an offset could otherwise have turned into a byte before the slice.
  • A test asserted that two different seeded hashes differ; that assertion is removed.

A second independent review (on f116a7e) found a torn read, fixed in df2678d:

  • Cause: the first write to an offset slice replaced its array and its offset in place.
  • Effect: a reader on another thread could pair the new array with the old offset. With s = base[1..] published to a reader and then s << "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.
  • Fix: offset slices are now immutable and replaced before their first write (see above).
  • Repro after the fix: 0 wrong and 0 errors in 10–21M reads, on net8.0 and net10.0, for suffix and prefix slices. Master: 0 and 0.
  • New test: MutableString_CopyOnWrite5 reproduces it in C#. With offset slices written in place again, it reports 150–1140 wrong reads.
  • Cost: a slice that is then appended to now copies once at the first write and again when it grows, the same as master. S.strip << "y" is back at master's figure, while strip, [n..] and byteslice themselves stay O(1).
  • Also in df2678d: 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:

  • full IronRuby.Tests: PASSED;
  • the matrix: 30,132 checks, identical to CRuby;
  • eql?/hash over all encodings: 0 mismatches;
  • the specs listed above: identical to master.

What to scrutinize

  • The invariant "_start != 0 ⇒ Shared", and that nothing clears Shared without resetting _start. Only EnterWriteSlow and Utils.RemoveShared's copying branch clear it.
  • Any read of _data that still assumes offset 0. grep -n _data in the two content classes: what is left without _start is either inside EnterWrite/ExitWrite or the constructors.
  • Retention: IsSharedSlice compares 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".
  • Hash: the AsciiRoundTrips predicate (identity and not dummy) and the 128 threshold have to agree between BinaryContent.CalculateHashCode and Content.HashCharacters. Hash values of long ASCII strings change, and long ASCII MutableStrings no longer equal System.String.GetHashCode; the doc comment is updated.
  • String#[] and slice! now return a GetSlice result instead of an appended copy. The encoding and ASCII flags come from GetSlice.

🤖 Generated with Claude Code

Largo and others added 2 commits November 10, 2026 20:28
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]>
@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 76 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 61bb889 and df2678d.

Files ignored due to path filters: 1

  • Src/Libraries/Initializers.Generated.cs is excluded by !**/*.generated.*
Files selected for processing: 13

  • Src/IronRuby.Tests/RubyTests.cs
  • Src/IronRuby.Tests/Runtime/MutableStringTests.cs
  • Src/Libraries/Builtins/MutableStringOps.cs
  • Src/Libraries/Extensions/ClrStringOps.cs
  • Src/Ruby/Builtins/MutableString.BinaryContent.cs
  • Src/Ruby/Builtins/MutableString.CharArrayContent.cs
  • Src/Ruby/Builtins/MutableString.Content.cs
  • Src/Ruby/Builtins/MutableString.StringContent.cs
  • Src/Ruby/Builtins/MutableString.cs
  • Src/Ruby/Builtins/RubyBufferedStream.cs
  • Src/Ruby/Builtins/RubyEncoding.cs
  • Src/Ruby/Runtime/RubyUtils.cs
  • Src/Ruby/Runtime/Utils.cs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment thread Src/Ruby/Runtime/RubyUtils.cs Resolved
Largo and others added 3 commits November 10, 2026 21:56
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]>
greptile-apps[bot]
greptile-apps Bot previously approved these changes Nov 10, 2026
…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]>
@greptile-apps
greptile-apps Bot dismissed their stale review November 10, 2026 21:29

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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 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.

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.

Fix in Claude Code

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant