Skip to content

Proposal: transfer package for v2.0.0 #1651

Closed

Description

@ttaylorr

This issue proposes a new design for the transfer package, which will supersede the lfs/transfer_queue.go code and serve as the sole mechanism to transfer objects to and from LFS servers.

Motivation

The current transfer-queue lacks some features that we’d like to implement for the v2.0.0 release of Git LFS:

  1. Less buffering. LFS should be better at dealing with really large working trees during initial pushes, or push —all’s. Currently, when retrying an object, it is re-inserted at the last spot in the queue, meaning that we could be holding a potentially large number of OIDs in memory before retrying them.
  2. Async. Currently, we have to wait for the entire working tree scan to complete before beginning the transfer. This is fine for small trees, but yields undesirable behavior for larger ones. We should be able to start uploading as soon as we have enough data to do so.
  3. Backpressure. We should synchronize the work being done by the scanner package with the work being done by the transfer package in uploading objects that the scanner finds. In other words: if we’re network-bound while uploading, we should delay scanning for more objects until we can resume uploading.
  4. Resumable transfers, by default. We should be able to resume uploads and downloads as the default if a transfer fails part-way through. This, combined with better retry behavior will yield for much more resilient and efficient transfers.
  5. Better design. Designing a new package for the transfer code, thus moving it out of the lfs package affords us the opportunity to re-imagine it from first principles, and define a solid, public API that can be used from other packages, and other programs.

Proposal

What follows is a high-level overview of the mechanism I’d like to implement in the scanner package, and a description of each of its major components (+ how it relates to the motivations above):

Async & backpressure

We should halt the scanning process when there are no available workers free to transfer objects. We can do this by using the following flow:

  1. Accept items using a <-chan *lfs.Pointer to build up a single batch of items
  2. If the currently accumulating batch has a cardinality smaller than twice the desired size of a batch (2*100), OR if the <-chan remains open, go to step 1.
  3. Make a batch API call with the accumulated items
  4. Distribute the transfers across n workers.
  5. While all workers are busy, go to step 4.
  6. As soon as a worker is free, go to step 1.
  7. Repeat until the <-chan *lfs.Pointer signals that there are no more items.

What’s great about this model is that we put back-pressure on the incoming channel of data when all the workers are busy, and we have a batch enqueued. Since the scanner’s implementation uses channels, the back-pressure propagates all the way up, halting the process of scanning revisions until it makes sense to continue that work.

Less buffering, retrying

I believe that there are two classifications of errors: resumable, and others. @technoweenie has provided some excellent commentary on the matter:

  • Fatal errors: errors that can’t be recovered from.
    • Examples: failing to read an object, write to a media file, or similar.
  • Local/recoverable errors: if the object is expired, or we experienced a network hiccup in the middle of transferring a file, let’s resume from there.

We can be clever in how we handle these: fatal errors should be exited immediately, and not retried in the future. To signal these, we can use the errors.NewFatalError or similar to indicate that the error returned from an adapter implementation cannot and should not be retried in the future.

In the case of recoverable errors, this is where things get interesting: we should make an attempt to retry those errors within the adapter unless it requires that we make another batch API call. For instance, a network hiccup should be retried internally before giving up and re-trying the batch call. On the other hand, an expired object needs another batch API call to get a new storage endpoint, so we must reject that immediately and retry.

Budgeting

Previously, our approach has been to try and keep track of the number of retries an object has attempted per OID. This has worked OK, but does not necessarily align well with our goals of making the transfer queue better at handling large numbers of unique OIDs, since the map[string]uint64 will grow linearly with the number of OIDs in the queue.

The way I see it, we have two approaches on what we can do:

  1. Retain the same cost-based approach per OID, purging the key from the cache when we give up on the OID. If we apply the constraint that the adapter does not accept non-unique OIDs, we should be fine to adopt this model.
  2. Use a cost-based approach per transfer queue, budgeting against all objects in the queue, not per OID. This approach could work, but it may be better to just treat the map with care, and adopt the first approach instead.

Retrying

The only way we can avoid buffering a potentially huge amount of OIDs is to retry them immediately, rather than later.

To accomplish this, I propose two return avenues for adapter implementations: one for new items and one for retried ones. The retry channel would be preferred and that would buffer old items before accepting new ones.

func acceptQueue() {
        for {
                var oid string
        
                // Try first to grab something from the retries
                // channel. If nothing was available, bail out
                // immediately
                select {
                case oid = <-retriesCh:
                default:
                }
                
                if len(oid) == 0 {
                        // If we didn't get an item to retry,
                        // search for a new one incoming
                        oid = <-newItems
                }
                
                if err := enqueue(oid); err != nil { … }
        }
}

This allows us to continue putting back-pressure all the way up the scanner implementation while we try and handle retries before accepting new items.

Resumable transfers

I like the existing transfer adapter design. What I’m proposing is similar, a different implementation of a transfer adapter interface for each transfer medium, Tus.io, Basic, and Custom:

package transfer

type Direction byte

const (
        Upload Direction = iota
        Download
)

type Adapter interface {
        Transfer(p *lfs.Pointer, d Direction, offset uint64) (n int, err error)
}

Better design

Implementing this mechanism in a brand new package, transfer, we afford ourselves the opportunity to redesign its public API to be stable, and easily consumable not only from other packages, but other programs as well.

In addition, and perhaps more importantly, considering new designs makes it easier to add tests at the unit and integration level, better ensuring the long-term stability of this crucial part of LFS.


Curious to hear your thoughts!

/cc @technoweenie @rubyist @larsxschneider @sinbad @sschuberth

Activity

  1. added this to the v2.0.0 milestone on Nov 14, 2016
  2. technoweenie commented on Nov 15, 2016

    @technoweenie
    Contributor

    Since this design lets us retry objects after network failures in a tighter loop in the worker, we should lower the dial/tls timeouts. Also, I don't think we need to do any fancy cost based stuff.

    • Fatal errors halt the command immediately.
    • Auth/token errors move it to the retry queue immediately.
    • Timeout and early disconnection issues just retry in the worker, and eventually move to the retry queue.

    Do you plan to start in a new transfer package? It may be okay, since testing http stuff in go tests is way easier than git through os/exec :) But, I really like being able to slowly evolve the scanner in baby steps so I can be sure it continues to work.

    Also, your diagram shows Add(t Transferable). Since this will be a new package, what do you think about just giving it some arguments, like Add(d Direction, oid string, size int64)? That way we won't have to convert from a gitscanner.Pointer to a transfer.Pointer (or at least, that part is hidden away inside the transfer pkg).

  3. ttaylorr commented on Nov 15, 2016

    @ttaylorr
    ContributorAuthor

    Also, I don't think we need to do any fancy cost based stuff.

    👍 , works for me.

    Timeout and early disconnection issues just retry in the worker, and eventually move to the retry queue.

    We can probably just keep track of the number of retries on the *lfs.Pointer, or whatever object it ends up being and promote local errors to fatal ones when we've exceeded our retry count.

    Do you plan to start in a new transfer package?

    Was thinking that we could evolve the current design and the move it all over at once.

    Also, your diagram shows Add(t Transferable). Since this will be a new package, what do you think about just giving it some arguments, like Add(d Direction, oid string, size int64)

    Not sure if how I feel about giving it a d Direction, but I think this makes much more sense from a decoupling perspective than binding it to *lfs.Pointer, *gitscanner.Pointer, or etc.

  4. sinbad commented on Nov 21, 2016

    @sinbad
    Contributor

    Please can we not lock down the transfer interface so tightly to an offset like this:

    type Adapter interface {
            Transfer(p *lfs.Pointer, d Direction, offset uint64) (n int, err error)
    }
    

    The existing custom adapter system is deliberately designed to give adapter implementors the freedom to do something other than a simple byte restart offset. The benefits of this is that it enables custom adapters to do de-duplication and chunk based restarting, where block sizes are entirely controlled by the adapter.

    This kind of approach to data management is extremely common in large file storage systems (see Dropbox and basically any cloud drive implementation), and Atlassian uses it in production already. The proposed interface is too specific and would completely remove the ability to use any more advanced transfer mechanism other than HTTP byte restart which would be a major step backwards. Let's not do this!

    In addition to not limiting transfer adapters to the simplest restart mechanism, the existing adapter interfaces also frees adapters to do their own parallelism internally, which this also takes away. Again I already use this in production with a custom adapter to sub-divide & parallelise files even further. Again this is not unusual in this space - imagine a P2P implementation of an LFS adapter.

    I understand the desire to lock down the interface but integration points like this need to be carefully considered not just from an internal cleanliness perspective but how they offer the most benefits externally; otherwise there's no point having extension points. It's beneficial to define them at a high enough level that external implementors have enough freedom to adapt them to new approaches, rather than being constrained to a single possible (logical) implementation.

  5. sinbad commented on Nov 21, 2016

    @sinbad
    Contributor

    Having said that, if you wanted to define the interface for basic and tus more tightly, because those do only need to use a byte offset and could have the rest of their logic externalised, that would be fine.

    But for the custom adapter, it needs to retain the ability to control the process at a higher level, i.e. to simply be given a stream of files to transfer, and to decide internally how to deal with them - including but not limited to sub-dividing them, deciding how/where to restart, implementing de-duplication systems internally, and so on. It should not be forced to deal with things in a serial 'start at byte X and do the rest' manner.

  6. ttaylorr commented on Nov 21, 2016

    @ttaylorr
    ContributorAuthor

    The proposed interface is too specific and would completely remove the ability to use any more advanced transfer mechanism other than HTTP byte restart which would be a major step backwards.

    I definitely agree that this is a valid concern: this was an oversight on my part.

    I thought for a while about encoding the offset onto the Transferable itself for a while, but I think this has a few problems:

    1. "Immutable mutability": the Transfer instance that we'd return from the transfer adapters would be different, but contain mostly the same information. This, to me, is only one notch away from mutating the underlying instance itself, and is 👎
    2. Same concerns: when would we send the Transferable into the adapter? If we're encoding the same information, I don't know if this solves the problem.

    In addition to not limiting transfer adapters to the simplest restart mechanism, the existing adapter interfaces also frees adapters to do their own parallelism internally, which this also takes away.

    Another thing to think about is whether or not this is a concern for LFS right now. I would argue that it's not, suggesting that we could specify the interface like this. On the other hand, I think keeping the interface open is important for outside contribution, and for our own use. Given that the goal of this refactor is to not have to do it again in six months, this doesn't seem like an appropriate solution to me either.

    Having said that, if you wanted to define the interface for basic and tus more tightly, because those do only need to use a byte offset and could have the rest of their logic externalised, that would be fine.

    I think this seems like a fair middle-ground. We can check which method the adapter implements, and send it a signal based on that. It's not my first choice, especially because we don't have any complex transfer mechanisms that go beyond a byte-offset, but I think this would be fine:

    type SimpleTransferAdapter interface {
            Transfer(t Transferable, d Direction, offs uint64) error
    }
    
    type ComplexTransferAdapter interface {
            Transfer(t Transferable, d Direction) error
    }
    
    func (q *TransferQueue) SendToAdapter(t Transferable, offs uint64) {
            var err error
    
            switch a := q.adapter.(type) {
            case SimpleTransferAdapter:
                    err = a.Transfer(t, q.direction, offs)
            case ComplexTransferAdapter:
                    err = a.Transfer(t, q.direction)
            }
    
            if err != nil {
                    // ...
            }
    }

    My preference, however, would be to solve this another way. The best we can do to get compile-time guarantees about implementations of the adapters is to either place a tag type on them, or give the guarantee up entirely and store them as an interface{}, which I would like to avoid.


    In short, I'm at a bit of a loss here. I see a bunch of things that we could do (as above), but all of them with their set of drawbacks. I think it may be best to settle on the {Simple,Complex}TransferAdapter design I posted above unless we come up with something better.

    At the very least, I think there is another week or so before I actually get to the adapters, so we have some time here 👍

  7. ttaylorr commented on Nov 21, 2016

    @ttaylorr
    ContributorAuthor

    UPDATE: @technoweenie dropped some major 💭 💣 on me and I think most of these issues are resolve-able easily. I'll post a some more thoughts shortly. 👍

  8. sinbad commented on Nov 21, 2016

    @sinbad
    Contributor

    Understand you may have further thoughts on this but time zones etc, I'll quickly add some emphasis:

    Another thing to think about is whether or not this is a concern for LFS right now.

    Bear in mind that Atlassian are already using the current capabilities of the custom adapter right now in production - both the ability to decide for ourselves what granularity to resume at, and to parallelise separately on top of anything Git LFS does. This is because we're implementing a block-based de-duplication system very much like Dropbox does. So changing these interfaces is not just an academic exercise for us, it will break a real-world implementation if the interface is made less flexible.

    It's not my first choice, especially because we don't have any complex transfer mechanisms that go beyond a byte-offset

    Please don't assume that just because it's not implemented in the core, no-one's using it. We are. When I wrote the custom transfer system we had extensive review and it wasn't a beta, it was an official feature.

  9. ttaylorr commented on Nov 21, 2016

    @ttaylorr
    ContributorAuthor

    Please don't assume that just because it's not implemented in the core, no-one's using it. We are.

    My apologies. After talking with @technoweenie, I think we can do this in a way that wont break any existing implementation, because it shouldn't require any interface changes:

    In the "basic" case, where we're using byte offsets to download objects, we can just check the amount that we've downloaded so far by stat-ing the file in disk, and seeing how much data we have. In the Tus.io upload case, we accomplish this by making a HEAD request.

    In other words: we can solve this problem by not having it and forcing the transfer adapters determine the offsets for themselves, if they need it.

    That means that custom transfer adapters, like the ones that you have at Atlassian, can remain unchanged.

  10. sinbad commented on Nov 21, 2016

    @sinbad
    Contributor

    Great, thanks. Just need to be a bit careful about assumptions; for example even if a custom adapter is totally controlling the download/upload it will still be posting progress updates, so the client can display them, but git-lfs itself won't see any of the actual data until the file is 100% completed. That's an important distinction because it frees the adapter to fetch/send blocks of the file out of order, re-use them from other places, skip them, etc. All that matters is that at the end of the day the file is re-assembled intact at the other end. To avoid having to make git-lfs aware of all the possible ways of doing that, for the custom adapter it only has a boolean view of a file: TODO or DONE. The adapter itself is then free to store unfinished data as fits its model; we do that with a db of incomplete blocks tailored to how our systems works, other systems could tailor it to their needs too.

    I really do think that some kind of P2P implementation could be awesome. Having cache servers for large distributed teams is quite common in other systems to improve the chances that content is close to where you need it, but what if you didn't need to configure an actual server for a satellite office, and instead all members of the team just shared file blocks automatically? Blocks rather than whole files to increase re-use over small edits. Would love to play with this idea sometime.

    Anyhow, thanks for putting my mind at rest.

  11. ttaylorr commented on Dec 13, 2016

    @ttaylorr
    ContributorAuthor

    Tracking #1764.

  12. ttaylorr commented on Dec 16, 2016

    @ttaylorr
    ContributorAuthor

    Merged as of #1780. 🎉

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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions