Skip to content

PipeReader.ReadAsync can return empty segments #30786

Closed

Description

@Trolldemorted

I just noticed that segments in a ReadResult can be empty:

grafik
I assumed that the first segment was never empty, so I often use result.Buffer.First.Span[0]; to access the first byte.

Is this intended behaviour? Can this be caused by me writing to the pipe in a wrong way? This is how I fill my pipe from a System.IO.Compression.DeflateStream:

private async Task Decompress(PipeWriter writer, ReadOnlyMemory<byte> data, int count)
{
    InflateInputStream.Position = 0;
    InflateInputStream.Write(data.Span.Slice(0, count));
    InflateInputStream.Position = 0;
    InflateInputStream.SetLength(count);
    int read;

    do
    {
        Memory<byte> memory = writer.GetMemory(data.Length * 2);
        read = InflateOutputStream.Read(memory.Span);
        writer.Advance(read);
    }
    while (read != 0);
    await writer.FlushAsync();
}

Activity

  1. jkotalik commented on Sep 6, 2019

    @jkotalik
    Contributor

    @davidfowl @pakrym IIRC I believe this behavior can happen based on how the pipe advances internally. I remember you two had a conversation about it. Is it possible to check if the first segment is empty before returning the ReadResult?

  2. Trolldemorted commented on Sep 6, 2019

    @Trolldemorted
    Author

    Just FYI, this behaviour does not occur in my setup if I read the inflate stream's output into a dedicated buffer, and WriteAsync the buffer into the pipe.

  3. davidfowl commented on Sep 6, 2019

    @davidfowl
    Member

    Ugh yes we need to try to solve the empty segment problem. It’s a real PITA to deal with that today. Honestly I’d rather try to fix it with ReadOnlySequence itself but we’d need to measure the impact.

  4. jkotalik commented on Sep 6, 2019

    @jkotalik
    Contributor

    but we’d need to measure the impact.

    What impact would it have?

  5. pakrym commented on Sep 6, 2019

    @pakrym
    Contributor

    ROS is very performance sensitive and we would have to add empty segment skipping code to multiple very hot paths (construction, First, enumeration etc)

  6. davidfowl commented on Sep 8, 2019

    @davidfowl
    Member

    I think we should at the very least try to avoid empty segments while building up the structure internally.

  7. pakrym commented on Sep 8, 2019

    @pakrym
    Contributor

    Wonder if we should make it a rule, don't produce ROS<> with empty segments. We won't be able to assert it unfortunately.

  8. jkotalik commented on Sep 10, 2019

    @jkotalik
    Contributor

    I think that rule works except when the ROS<> is empty.

    @Trolldemorted From what I can tell, this potentially was fixed in 3.0. Could you try the latest 3.0-preview9 release and see if you hit this behavior again? https://dotnet.microsoft.com/download/dotnet-core/3.0.

    edit: We believe dotnet/corefx@34765c5 should have fixed this issue. Please let us know if you are continuing to see this behavior.

  9. davidfowl commented on Sep 10, 2019

    @davidfowl
    Member

    @Trolldemorted can you show how you created the Pipe? In particular I want to see the PipeOptions

  10. Trolldemorted commented on Sep 10, 2019

    @Trolldemorted
    Author

    @jkotalik just making sure, you want me to upgrade to sdk preview9, but keep System.IO.Pipelines on the latest stable release (4.5.3)? Was 34765c5 landed in the sdk? I upgraded the SDK to 3.0.100-preview9-014004 and kept System.IO.Pipelines 4.5.3 but it happened again. I also noticed other segments can be empty too:
    grafik

    @davidfowl I am using new Pipe() with no explicit options (source).

  11. davidfowl commented on Sep 11, 2019

    @davidfowl
    Member

    @Trolldemorted you need to update the package to preview9 of System.IO.Pipelines

  12. Trolldemorted commented on Sep 11, 2019

    @Trolldemorted
    Author

    I upgraded to 4.6.0-preview9.19421.4, but it still happens. Might be my imagination but it happens less frequently, though.

  13. davidfowl commented on Sep 11, 2019

    @davidfowl
    Member

    @Trolldemorted if you can provide a repro (set of steps to reproduce the empty segments) that would be great. It would mean logging what you wrote and how you called AdvancedTo on the other side.

  14. Trolldemorted commented on Sep 11, 2019

    @Trolldemorted
    Author

    A repro for an empty first segment is tricky, as they happen pretty rarely (last time after >2GB of input). However, I found a small input for an empty non-first segment:

    https://github.com/Trolldemorted/EmptySegmentsBug/blob/371c7ceca7412f4313257c720965162a1b56ae76/EmptySegmentsBug/Program.cs

    If you have VS and dotnet core 3 preview9 installed, opening it and pressing F5 should throw the "segment empty!" InvalidDataException, at least it does that reliably on my laptop.

    Thanks a lot for your patience!

  15. marklio commented on Sep 11, 2019

    @marklio

    Marking this as reliability, as First.Span[0] and FirstSpan[0] are extremely common when processing ROS.

  16. 9 remaining items

  17. added this to the Future milestone on Jul 8, 2020
  18. removed
    untriaged
    on Jul 8, 2020
  19. Trolldemorted commented on Oct 9, 2020

    @Trolldemorted
    Author

    A year has past, can you estimate when this will be fixed? I see you removed it from the 5.0 milestone, which is unfortunate.

  20. freddyrios commented on Feb 9, 2022

    @freddyrios

    so, what's the idiomatic way to get the first byte, since this is unsafe: ros.First.Span[0]
    what about the second byte, is this also problematic? ros.Slice(1).First.Span[0]

  21. Trolldemorted commented on Jul 18, 2022

    @Trolldemorted
    Author

    any chance we get a fix for 7.0?

  22. davidfowl commented on Jul 18, 2022

    @davidfowl
    Member

    @Trolldemorted How did you reproduce it?

  23. davidfowl commented on Jul 19, 2022

    @davidfowl
    Member

    So I upgraded the repro to use netcoreapp3.1 and the System.IO.Pipelines 6.0.3 and I get an empty segment at the end. When I upgrade to .NET 6 the problems goes away (likely from changes to the Stream).

    PS: The code is also incorrect here, it should be:

    if (result.Buffer.Length == 0 && (result.IsCanceled || result.IsCompleted))
    

    We should fix any bugs that result in the PipeReader producing empty segments though. Narrowing down this repro on .NET Core 3.1 more might help figure out the exact reason why there's an empty segment at the end.

  24. davidfowl commented on Jul 19, 2022

    @davidfowl
    Member

    OK I have a repro. Generally when the length is passed into GetMemory we need to handle the case where's there's an existing segment allocated with nothing written into it, but more space is being requested than is available:

    using System;
    using System.IO.Pipelines;
    using System.Threading.Tasks;
    
    namespace EmptySegmentsBug
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var pipe = new Pipe();
                
                // Get a new block but don't write anything
                var buffer = pipe.Writer.GetMemory();
                pipe.Writer.Advance(0);
                await pipe.Writer.FlushAsync();
    
                // Get a new block
                buffer = pipe.Writer.GetMemory(4096 * 2);
                pipe.Writer.Advance(buffer.Length);
                await pipe.Writer.FlushAsync();
    
                await ReadAndDump();
    
                async Task ReadAndDump()
                {
                    var result = await pipe.Reader.ReadAsync();
                    Console.Write("[");
                    bool first = true;
                    foreach (var segment in result.Buffer)
                    {
                        if (!first)
                        {
                            Console.Write(",");
                        }
    
                        Console.Write(segment.Length);
                        first = false;
                    }
                    Console.WriteLine("]");
                    pipe.Reader.AdvanceTo(result.Buffer.End);
                }
            }
        }
    }

    This prints: [0,8192]

  25. ghost added
    in-pr
    on Jul 20, 2022
  26. ghost removed
    in-pr
    on Jul 21, 2022
  27. modified the milestones: Future, 7.0.0 on Jul 21, 2022
  28. ghost locked as resolved and limited conversation to collaborators on Aug 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.IO.Pipelinestenet-reliability

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions