Skip to content

performance wins to investigate for the next release #7464

Closed

Description

@shiftkey

Please describe the problem you think should be solved

We got some feedback from some of our beta users that the app is not as performant as expected after the latest update. I'd like to propose investigating and seeing what we can address before the next update.

The feedback was focused on two areas:

  • macOS, repository with ~8000 refs, application is very sluggish
  • Windows, new stash workflows are not as performant as expected

My personal goals as part of this investigation:

  • skip unnecessary work where possible
  • tune the work we have to do so it runs better under extreme cases
  • better guard against concurrent refreshing

[Optional] Do you have any potential solutions in mind?

I paired on this today with @iAmWillShepherd and @outofambit to talk through what we've seen and what we could focus on in the short term, and we came up with some areas to further explore and optimize.

These items are grouped based on when we believe they were introduced into the codebase, with regressions in the beta releases prioritized before problems that exist in the current production release:

Regressions on beta

Overlapping getStatus calls introduce a bottleneck - #7471 - 🚢

We identified these chain of calls into getStatus that can overlap:

  • checkoutBranch -> AppStore.refreshRepository -> AppStore._loadStatus -> gitStore.getStatus
  • popStashEntry -> AppStore.refreshRepository -> AppStore.refreshIndicatorsForRepositories -> AppStore.refreshIndicatorForRepository -> AppStore._loadStatus -> gitStore.getStatus

getStatus itself performs a lot of additional work to git status:

  • checking for merge/rebase conflict state
  • checking for conflicted files in working directory
  • checking for binary files in working directory

This feels like a situations where a "refresh" doesn't need to refresh everything, and callers might want to opt-out of updating indicators (or pass in the known state to do the updating).

Reuse getStatus result when refreshing to update indicators - #7475

Building on the above problem, calling AppStore._refreshRepository will result in two AppStore._loadStatus calls:

The first is in refreshRepository itself:

const status = await this._loadStatus(repository)

The second is in AppStore.refreshIndicatorsForRepositories (the original intent here was to have the same behaviour whether this was an active repository or not):

this.refreshIndicatorsForRepositories([repository], false)

Because we're working with the current repository, and all that this function does is update an indicator in the sidebar - not the most urgent thing to keep up to date for the user - I propose replacing the AppStore.refreshIndicatorsForRepositories call with something to reuse the previous AppStore._loadStatus result to save on a bunch of Git operations.

only stash when checkout fails with a warning - #7474

The original stashing MVP had this workflow "try checkout, if that triggers then prompt to do stashing" which was great for happy-path scenarios where stashing isn't needed. We eventually moved away from that into "stash, checkout, then pop the stash" which is more conservative but takes more time whenever a user changes branches with uncommitted changes.

There may be an opportunity here to avoid a lot of unnecessary stashing work to help speed up the happy path flow.

getFilesWithConflictMarkers and getBinaryPaths are run when not in conflict state - #7476 - 🚢

As part of invoking getStatus the details about conflicts are included (helping to indicate which files are resolved, and which files require manual conflicts). In #7380 we added detection to help support stashes that introduce conflicts, but these function now always fire when there are changes - even when there are conflicts. In extreme cases, these functions can take multiple seconds each, and adversely impact refreshing.

We should tune the criteria for how this fires so that it only runs when necessary.

Existing behaviour on production

getRemotes is not cached in GitStore

We cache the defaultRemote, currentRemote and upstreamRemote in GitStore, but not the list of remotes itself. I count multiple usages of this that could defer to the currently cached set, because of how little this will churn for a user.

Benefits: fewer Git process calls on Windows, better caching of repository state

getBranches does not need to enumerate Desktop forks

In getBranches we have this workaround to hide forks created as part of maintaining PR flow:

if (ref.startsWith(ForksReferencesPrefix)) {
// hide refs from our known remotes as these are considered plumbing
// and can add noise to everywhere in the user interface where we
// display branches as forks will likely contain duplicates of the same
// ref names
continue
}

This means we are enumerating some refs in git for-each-ref to then throw the result away, which feels like a chance to do better.

We could add in a new function to explicitly indicate which remote refs to enumerate, instead of using refs/remotes/*, and exclude

Benefits: less work done for users who are frequently checking out PR forks locally. Users with thousands of refs not managed by Desktop will not see significant improvements.

tune getBranches to work quicker with thousands of refs

We get a lot of information inside getBranches using the --pretty parameter:

const format = [
'%(refname)',
'%(refname:short)',
'%(upstream:short)',
'%(objectname)', // SHA
'%(objectname:short)', // short SHA
'%(author)',
'%(committer)',
'%(parent)', // parent SHAs
'%(symref)',
'%(subject)',
'%(body)',
'%(trailers:unfold,only)',
`%${delimiter}`, // indicate end-of-line as %(body) may contain newlines
].join('%00')

But in our branch switcher we only show a minimal set of information:

For a repository with ~7000 refs, the work required to git for-each-ref without any --format looks like this:

$  time git for-each-ref --format="%(refname)" refs/heads refs/remotes
...
git for-each-ref --format="%(refname)" refs/heads refs/remotes  0.06s user 0.26s system 95% cpu 0.336 total

But with the full set of information that Desktop needs currently, the time is significantly increased:

$ time git for-each-ref --format="%(refname)%00%(refname:short)%00%(upstream:short)%00%(objectname)%00%(objectname:short)%00%(author)%00%(committer)%00%(parent)%00%(symref)%00%(subject)%00%(body)%00%(trailers:unfold,only)%00" refs/heads refs/remotes
...
git for-each-ref  refs/heads refs/remotes  0.34s user 1.16s system 94% cpu 1.584 total

This is invoked as part of every refreshRepository, and I wonder if we can make this function return just what Desktop actually needs, and throw away some of the extra information.

cache git config values

As part of refreshing the repository we look at these config values:

  • trailer.separators - for identifying co-author information
  • pull.rebase for hinting when a "pull with rebase" will occur

We also look at this value before doing any push/pull/fetch operation

  • protocol.version

We could merge these checks into a single git config check, and cache this in the GitStore for use when needed in the app, using the same refresh rules as our other Git operations. This will require some way to pass this configuration into Git operations, but given how often these values are likely to change I think this is worth exploring.

Activity

  1. added
    performance
    meta
    on May 3, 2019
  2. billygriffin commented on May 3, 2019

    @billygriffin
    Contributor

    Thanks for the writeup @shiftkey! Would you mind sharing which of these things are regressions since 1.6.5? My impression is that it's only the stashing one when selecting to bring your changes with you to a new branch, but just want to ensure that's actually the case. In other words, all of these seem like legitimate performance concerns, but most of them exist whether someone is using 1.6.5 prod or the most recent beta, correct?

  3. shiftkey commented on May 3, 2019

    @shiftkey
    MemberAuthor

    These are regressions related to new features:

    • Overlapping getStatus calls introduce a bottleneck
    • only stash when there are problems with checkout

    The others are more noticeable because of how these new features are refreshing the app, or were uncovered while investigating related areas.

  4. nerdneha commented on May 6, 2019

    @nerdneha
    Contributor

    Hi all, I think this issue does a great job at laying out all the problems and is a great launching point for anyone who will eventually get started on any of these areas.

    One thing that’s missing for me is having the right information side-by-side in order to make a good decision around what to deliver for 1.7 and what can be put into a later release.

    What if we added a summary table at the bottom where each suggestion can be filled out with pertinent info needed for prioritization. One thing that @billygriffin mentioned that would be helpful for him is “regression since 1.6.5?” as one of the pieces of info that could be filled out for each suggestion. What other info would be good to add? This is our first time doing this so I think it’s a valuable exercise to try out.

  5. shiftkey commented on May 6, 2019

    @shiftkey
    MemberAuthor

    @nerdneha thanks for the suggestions. I want to give @iAmWillShepherd and @outofambit a chance to get involved with their own findings and suggestions before going further. We talked about this late on Friday and I wanted to open up something as a starting point for discussion, and I'll work with them to aggregate and organize things into a more concise list.

  6. iAmWillShepherd commented on May 6, 2019

    @iAmWillShepherd
    Contributor

    The original stashing MVP had this workflow "try checkout, if that triggers then prompt to do stashing" which was great for happy-path scenarios where stashing isn't needed. We eventually moved away from that into "stash, checkout, then pop the stash" which is more conservative but takes more time whenever a user changes branches with uncommitted changes.

    @iAmWillShepherd knows more about the tradeoffs here so I'll ask him to add more context here, but I think we wanted to look into what gains we'd get by doing "checkout, see if it fails" and then doing "stash, checkout, then pop stash" as a fallback (i.e. when it's actually needed).

    There are no trade-offs related to performance with using the approach described above. There is, however, UX trade-off. Specifically, the original design spec for stashing indicated that the dialog to stash uncommitted changes be shown every branch checkout. If we move to the way stashing was originally going to be implemented, then it wouldn't comply with the intended design.

    While I think it would be better to only show the stash dialog when Desktop cannot successfully checkout branch due to uncommitted changes being present because it would reduce the amount of work that needs to be done as @shiftkey explained, we would lose the ability to explicitly stash changes on the current branch if the branch being checkout isn't ahead of the current branch. In other words, if a user wanted to stash some changes, there is the possibility they wouldn't be given the opportunity to since stashing is only activated on branch checkout. I think more exploration would need to be done around the UX of stashing before making any changes to its workflow.

  7. shiftkey commented on May 6, 2019

    @shiftkey
    MemberAuthor

    Specifically, the original design spec for stashing indicated that the dialog to stash uncommitted changes be shown every branch checkout. If we move to the way stashing was originally going to be implemented, then it wouldn't comply with the intended design.

    This all makes sense, but what if we were able to adhere to the UX but adjust the underlying technical implementation?

    Let me walk through the two options we display, and how it could work under the hood...

    • Leave my changes on [current branch]

    This one requires stashing to keep the changes around while we do other work, before then running checkout to switch branches. We shouldn't change this because we don't have an alternative that's satisfactory.

    • Bring my changes to [new branch]

    What if we changed up the order of operations?

    1. Try and checkout the other branch with the working directory changes. If it works without errors, we're done.
    2. Because we know the checkout didn't succeed, we now stash the changes, checkout the branch, then pop the stash. If this works without errors, we're done.
    3. You have stash conflicts to resolve before proceeding to whatever you were meaning to do?

    In other words, if a user wanted to stash some changes, there is the possibility they wouldn't be given the opportunity to since stashing is only activated on branch checkout.

    I suggested revisiting the workflow not to skip showing the dialog to users, but to change the underlying implementation to lean more on how Git works and to potentially avoid Git operations when a checkout will occur without issues with the working directory state.

    I'll go through a detailed example to outline why I care so much about this. Here's the setup I'm using as a reference:

    commit 0982ed8d8dce585101ef631a40ac61bcd8737b54
    Author: Brendan Forster <[email protected]>
    Date:   Mon May 6 18:15:05 2019 -0300
    
        add some tweaks to make this easier to benchmark
    
    diff --git a/app/src/lib/feature-flag.ts b/app/src/lib/feature-flag.ts
    index aed2afb11..a7a2af479 100644
    --- a/app/src/lib/feature-flag.ts
    +++ b/app/src/lib/feature-flag.ts
    @@ -83,5 +83,5 @@ export function enableRebaseDialog(): boolean {
     
     /** Should the app show the "stash changes" dialog? */
     export function enableStashing(): boolean {
    -  return enableBetaFeatures()
    +  return true
     }
    diff --git a/app/src/ui/lib/git-perf.ts b/app/src/ui/lib/git-perf.ts
    index 3ac4d2dbb..9de3cfbe3 100644
    --- a/app/src/ui/lib/git-perf.ts
    +++ b/app/src/ui/lib/git-perf.ts
    @@ -18,7 +18,7 @@ export async function measure<T>(
     ): Promise<T> {
       const id = ++markID
     
    -  log.debug(`Executing ${cmd}`)
    +  //log.debug(`Executing ${cmd}`)
       const startTime = performance && performance.now ? performance.now() : null
     
       markBegin(id, cmd)
    @@ -27,10 +27,10 @@ export async function measure<T>(
       } finally {
         if (startTime) {
           const rawTime = performance.now() - startTime
    -      if (rawTime > 1000) {
    -        const timeInSeconds = (rawTime / 1000).toFixed(3)
    -        log.info(`Executing ${cmd} (took ${timeInSeconds}s)`)
    -      }
    +      //if (rawTime > 1000) {
    +      const timeInSeconds = (rawTime / 1000).toFixed(3)
    +      log.info(`Executing ${cmd} (took ${timeInSeconds}s)`)
    +      //}
         }
     
         markEnd(id, cmd)
    diff --git a/app/src/ui/stash-changes/stash-and-switch-branch-dialog.tsx b/app/src/ui/stash-changes/stash-and-switch-branch-dialog.tsx
    index 17c0b52d9..1fc297d0a 100644
    --- a/app/src/ui/stash-changes/stash-and-switch-branch-dialog.tsx
    +++ b/app/src/ui/stash-changes/stash-and-switch-branch-dialog.tsx
    @@ -148,10 +148,12 @@ export class StashAndSwitchBranch extends React.Component<
         this.setState({ isStashingChanges: true })
     
         try {
    +      console.time('stash flow')
           await this.stashAndCheckout()
         } finally {
           this.setState({ isStashingChanges: false }, () => {
             this.props.onDismissed()
    +        console.timeEnd('stash flow')
           })
         }
       }
    
    • build for release and run it up: yarn build:prod && yarn start:prod
    • using desktop/desktop (it's a non-trivial repository but not too complex)
    • create a new empty file at the repository root to trigger the flow
    • create a new branch off development
    • "Bring my changes to [new branch]"
    • time how long it is from "the user clicks" to "the app dismisses the dialog" (to suggest that they can proceed with their work)

    The results are pretty interesting. I've extracted the important bits related to stashing below:

    Executing createStashEntry: git stash push --include-untracked -m !!GitHub_Desktop<yes> (took 1.162s)
    ...
    Executing checkoutBranch: git -c credential.helper= checkout --progress yes -- (took 0.543s)
    ...
    Executing popStashEntry: git stash pop --quiet stash@{0} (took 0.848s)
    ...
    stash flow: 5987.911865234375ms
    

    Note that this includes #7471 (which is focused on avoiding unnecessary refresh work).

    Even going through the same steps on my MBP has some interesting details (I'm still curious where the remaining time is spent that isn't directly attributed to Git operations, cc @billygriffin):

    Executing createStashEntry: git stash push --include-untracked -m !!GitHub_Desktop<yes> (took 0.549s)
    ...
    Executing checkoutBranch: git -c credential.helper= checkout --progress yes -- (took 0.069s)
    ...
    Executing popStashEntry: git stash pop --quiet stash@{0} (took 0.313s)
    ...
    stash flow: 3227.589111328125ms
    

    My hypothesis currently is that we're doing unnecessary work for checkout (because checkout won't report an error in many/most cases) and we're wasting time with stashing-and-popping like we currently are.

  8. iAmWillShepherd commented on May 7, 2019

    @iAmWillShepherd
    Contributor

    @shiftkey, I took a stab at implementing the flow you described over in #7474. If you had any other ideas just let me know or push some commits to my branch 👍

  9. shiftkey commented on May 7, 2019

    @shiftkey
    MemberAuthor

    I've pushed up a couple of branches to help with poking at things and getting more information at runtime:

    • shiftkey/grouped-tracing-for-development - this branch adds more information to the Git operations occurring at development time, to help identify slow points in regressions
    • shiftkey/add-timings-to-production - this branch adds the same timing information to the last production release, so you can get a better apples-for-apples comparison

    A test case I have been poring over is using the nodejs/node repository and removing all the tracked files - 33k working directory changes.

    This is the breakdown in the Git work done while a refresh occurs on the latest production branch:

    Compare this to the current development branch:

    The added getFilesWithConflictMarkers and getBinaryPaths functions (highlighted in red), which were added in #7380 to support stashing, now make up a significant percentage of the refresh work. cc @outofambit for thoughts on whether we can avoid calling this as often as we are currently (is there a different .git/ file we can look for to detect when a stash has introduced conflicts?)

  10. shiftkey commented on May 7, 2019

    @shiftkey
    MemberAuthor

    cc @outofambit for thoughts on whether we can avoid calling this as often as we are currently (is there a different .git/ file we can look for to detect when a stash has introduced conflicts?)

    I'm going to pick this up as I think .git/ORIG_HEAD is a suitable flag to indicate the stash has introduced conflicts.

  11. outofambit commented on May 7, 2019

    @outofambit
    Contributor

    I'm going to pick this up as I think .git/ORIG_HEAD is a suitable flag to indicate the stash has introduced conflicts.

    @shiftkey i did look at that originally, but found it unreliably cleaned by git up in my testing. but if you find a way to use it, that would be great!

    i'm also looking into another "trigger" we could use: looking at the index status to see if any files are marked unmerged, both added, etc before we run further commands to gather more information.

  12. shiftkey commented on May 7, 2019

    @shiftkey
    MemberAuthor

    i'm also looking into another "trigger" we could use: looking at the index status to see if any files are marked unmerged, both added, etc before we run further commands to gather more information.

    @outofambit something something great minds think alike. I've got a PR on the way that will look very similar to this idea.

  13. shiftkey commented on May 7, 2019

    @shiftkey
    MemberAuthor

    @billygriffin @nerdneha I've updated the issue body to split them between known regressions and problems in things already shipped to production, and also linking items to in-flight PRs that we're discussing/reviewing.

    I think once those are reviewed and we're happy to cut a beta I think we'll be in a much better place.

  14. outofambit commented on May 20, 2019

    @outofambit
    Contributor

    It looks like we've either opened or merged PRs for all of the items under the "Regressions on beta" section and discussion has slowed otherwise so i'm going to close this issue. Thanks all!

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

    metaperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions