@@ -825,16 +825,35 @@ it.layer(
825825 sequences . map ( ( { prefix, terminator } ) => prefix + terminator + preserved ) . join ( "" ) +
826826 "done\n" ;
827827
828- for ( const { prefix, terminator } of sequences ) {
829- for ( let offset = 0 ; offset < prefix . length ; offset += 4_096 ) {
830- process . emitData ( prefix . slice ( offset , offset + 4_096 ) ) ;
828+ // Counts reads of strings larger than one emitted chunk, so rescanning the
829+ // pending prefix on every chunk (#23817) shows up as quadratic work.
830+ const charCodeAt = String . prototype . charCodeAt ;
831+ let largeStringReads = 0 ;
832+ yield * Effect . gen ( function * ( ) {
833+ // eslint-disable-next-line no-extend-native -- Count reads without retaining millions of spy call records.
834+ String . prototype . charCodeAt = function ( this : string , index : number ) {
835+ if ( this . length > 4_096 ) largeStringReads += 1 ;
836+ return charCodeAt . call ( this , index ) ;
837+ } ;
838+ for ( const { prefix, terminator } of sequences ) {
839+ for ( let offset = 0 ; offset < prefix . length ; offset += 4_096 ) {
840+ process . emitData ( prefix . slice ( offset , offset + 4_096 ) ) ;
841+ }
842+ process . emitData ( terminator + stripped + preserved ) ;
831843 }
832- process . emitData ( terminator + stripped + preserved ) ;
833- }
834- process . emitData ( "done\n" ) ;
835- yield * Deferred . await ( outputSeen ) ;
844+ process . emitData ( "done\n" ) ;
845+ yield * Deferred . await ( outputSeen ) ;
846+ } ) . pipe (
847+ Effect . ensuring (
848+ Effect . sync ( ( ) => {
849+ // eslint-disable-next-line no-extend-native -- Restore the counting hook even when the test fails.
850+ String . prototype . charCodeAt = charCodeAt ;
851+ } ) ,
852+ ) ,
853+ ) ;
836854 yield * manager . close ( { threadId : "thread-1" } ) ;
837855
856+ expect ( largeStringReads ) . toBeLessThan ( 2 * expected . length ) ;
838857 expect ( yield * readFileString ( yield * historyLogPath ( logsDir ) ) ) . toBe ( expected ) ;
839858 expect ( ( yield * manager . open ( openInput ( ) ) ) . history . startsWith ( expected ) ) . toBe ( true ) ;
840859 } ) ,
0 commit comments