Repository: sublimelsp/LSP

Issue:
[ST4] gopls: high memory usage and exit status 2 when switching projects 
## OS and language server

Arch Linux
gopls: `@v0.4.4 h1:8djGYsaZ0ByP0vaXg4T+mnyfDcHpWKSZ+tpQSGv9ahk=`
ST4: `4.4081-1`

## How you installed LSP (Package Control or from git?)

Git clone, `st4000-exploration` branch at 61f59a45.

## More information on the setup

### 3rd party plugin

I have a [project manager](https://github.com/randy3k/ProjectManager) plugin that would open/switch projects. 

### Projects setup

The projects has been setup with one path:

```json
{
    "folders":
    [
        {
            "path": "/path/to/project",
        },
    ],
    "settings":
    {
        "LSP":
        {
            "gopls": {"enabled": true}
        },
    }
}
```


Note that the project is in the `$GOPATH`, but the `GO111MODULE` is on.

### LSP settings

```json
{
    "auto_show_diagnostics_panel": false,
    "clients":
    {
        "gopls":
        {
            "command": ["gopls"],
            "enabled": true,
            "env":
            {
                "GO111MODULE": "on",
                "GOPATH": "/home/arsham/go:/usr/lib/go",
                "PATH": "/home/arsham/go/bin:$PATH:/usr/lib/go/bin:/usr/bin",
                "CGO_ENABLED": "0",
            },
            "languageId": "go",
            "scopes": ["source.go"],
            "settings":
            {
                "completeUnimported": true,
                "organizeImports": true,
                "usePlaceholders": true,
                "workspaceFolders": true,
            },
            "syntaxes": ["Packages/Go/Go.sublime-syntax"],
        }
    },
    "disabled_capabilities":
    [
        "completion",
    ],
    "log_debug": true,
    "log_payloads": true,
    "log_stderr": true
}
```

## Minimal reproduction steps

Install the project manager plugin. Open ST with one project, then "switch" to another project as explained below.

Let's call opening a project in a new window **opening a project**. This is done with the `Project Manager: Open Project in New Window` command. You will end up with two ST windows containing two separate projects.

And call it **switching to a project** when opening a project in the current windows, which is done with the `Project Manager: Open Project` command should behave like how ST4's stock behaviour.
Create two projects with the provided settings. Open one project, then switch to the other as explained in the next section.


## Observation

### Condition 1

Opening a project with this plugin works fine. No matter how many project I open, the memory usage remains almost the same. 

![ok](https://user-images.githubusercontent.com/428611/89884972-348cc300-dbc2-11ea-9349-8664ea0ba91b.jpg)

### Condition 2

Switching to a project opens a dialog saying `gopls exited with status code 2`. `Restart gopls` button causes this dialog to show up again in random times and the `gopls` server continues consuming memory in the background.

![not ok](https://user-images.githubusercontent.com/428611/89888179-710eed80-dbc7-11ea-9282-f4d41a023308.jpg)

### Condition 3

If both projects are open, and I try to switch in either windows, there are no problems. (like condition 1)

### Condition 4

I need the following settings in order to get LSP working on files outside of the project path. Places like in modules or SL.


```json
    {
      "name": "Standard Library",
      "path": "/usr/lib/go/src/",
      "file_exclude_patterns": ["*"],
      "folder_exclude_patterns": ["*"],
    },
    {
      "name": "Mod",
      "path": "/home/arsham/go/pkg/mod/",
      "file_exclude_patterns": ["*", "cache"],
      "folder_exclude_patterns": ["*"],
    }
```

Updating the project setting while the project is open has two different situation:

#### Condition 4.a

If the session started with condition 1 (no issues), these changes has no effect on memory usage.

#### Condition 4.b

If changes made after the `condition 2`, each change causes the issues in the `condition 2`.

## Logs

<details><summary>Console Logs</summary>
<p>

```
Traceback (most recent call last):
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 594, in <lambda>
    lambda: check_view_event_listeners(view))
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 584, in check_view_event_listeners
    listeners.append(cls(view))
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 148, in __init__
    self._sighelp_renderer = ColorSchemeScopeRenderer(self.view)
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 84, in __init__
    self._scope_styles[scope] = mdpopups.scope2style(view, scope)
  File "/home/arsham/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py", line 550, in scope2style
    style_obj = obj.guess_style(view, scope, selected, explicit_background)
AttributeError: 'NoneType' object has no attribute 'guess_style'
Traceback (most recent call last):
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 594, in <lambda>
    lambda: check_view_event_listeners(view))
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 584, in check_view_event_listeners
    listeners.append(cls(view))
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 148, in __init__
    self._sighelp_renderer = ColorSchemeScopeRenderer(self.view)
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 84, in __init__
    self._scope_styles[scope] = mdpopups.scope2style(view, scope)
  File "/home/arsham/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py", line 550, in scope2style
    style_obj = obj.guess_style(view, scope, selected, explicit_background)
AttributeError: 'NoneType' object has no attribute 'guess_style'
git: tracking working dir /home/arsham/Projects/Go/github.com/xxx/yyy
LSP: starting ['gopls'] in /home/arsham/Projects/Go/github.com/xxx/yyy
LSP: gopls: Supported execute commands: ['generate', 'fill_struct', 'regenerate_cgo', 'test', 'tidy', 'undeclared_name', 'upgrade_dependency', 'vendor', 'extract_variable', 'extract_function']
LSP: gopls: supported code action kinds: ['quickfix', 'refactor.extract', 'refactor.rewrite', 'source.fixAll', 'source.organizeImports']
LSP: starting ['gopls'] in /home/arsham/Projects/Go/github.com/xxx/yyy
LSP: starting ['gopls'] in /home/arsham/Projects/Go/github.com/xxx/yyy
LSP: gopls: Supported execute commands: ['generate', 'fill_struct', 'regenerate_cgo', 'test', 'tidy', 'undeclared_name', 'upgrade_dependency', 'vendor', 'extract_variable', 'extract_function']
LSP: gopls: supported code action kinds: ['quickfix', 'refactor.extract', 'refactor.rewrite', 'source.fixAll', 'source.organizeImports']
LSP: ['gopls'] ended
... the following repeats a lot:
LSP: starting ['gopls'] in /home/arsham/Projects/Go/github.com/xxx/yyy
LSP: gopls: Supported execute commands: ['generate', 'fill_struct', 'regenerate_cgo', 'test', 'tidy', 'undeclared_name', 'upgrade_dependency', 'vendor', 'extract_variable', 'extract_function']
LSP: gopls: supported code action kinds: ['quickfix', 'refactor.extract', 'refactor.rewrite', 'source.fixAll', 'source.organizeImports']
LSP: ['gopls'] ended
...
```

</p>
</details>


<details><summary>LSP Logs</summary>
<p>

```
gopls: 2020/08/11 11:26:28 Build info
----------
golang.org/x/tools/gopls 0.4.4
    golang.org/x/tools/gopls@v0.4.4 h1:8djGYsaZ0ByP0vaXg4T+mnyfDcHpWKSZ+tpQSGv9ahk=
    github.com/BurntSushi/toml@v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
    github.com/google/go-cmp@v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
    github.com/sergi/go-diff@v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
    golang.org/x/mod@v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
    golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
    golang.org/x/tools@v0.0.0-20200729181040-64cdafbe085c h1:jLQLIAedRoS9I2Py7l/ZAGGzUxLFsdg42JXEpS/a+ow=
    golang.org/x/xerrors@v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
    honnef.co/go/tools@v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
    mvdan.cc/gofumpt@v0.0.0-20200709182408-4fd085cb6d5f h1:gi7cb8HTDZ6q8VqsUpkdoFi3vxwHMneQ6+Q5Ap5hjPE=
    mvdan.cc/xurls/v2@v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A=

Go info
-------
go version go1.14.5 linux/amd64



gopls: 2020/08/11 11:26:28 go env for /home/arsham/Projects/Go/github.com/xxx/yyyy
(root /home/arsham/Projects/Go/github.com/xxx/yyyy)
(valid build configuration = true)
(build flags: [])
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOSUMDB=sum.golang.org
GOCACHE=/home/arsham/.cache/go-build
GOPROXY=https://proxy.golang.org,direct
GOMOD=/home/arsham/Projects/Go/github.com/xxx/yyyy/go.mod
GOMODCACHE=
GO111MODULE=on
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GOFLAGS=-tags=integration
GOINSECURE=
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOROOT=/usr/lib/go


gopls: 2020/08/11 11:26:28 go env for /usr/lib/go/src
(root /usr/lib/go/src)
(valid build configuration = true)
(build flags: [])
GOROOT=/usr/lib/go
GO111MODULE=on
GOFLAGS=-tags=integration
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct
GOINSECURE=
GOMODCACHE=
GOCACHE=/home/arsham/.cache/go-build
GOMOD=/usr/lib/go/src/go.mod
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GOSUMDB=sum.golang.org


gopls: 2020/08/11 11:26:28 go env for /home/arsham/go/pkg/mod
(root )
(valid build configuration = false)
(build flags: [])
GOFLAGS=-tags=integration
GOMODCACHE=
GOSUMDB=sum.golang.org
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct
GO111MODULE=on
GOCACHE=/home/arsham/.cache/go-build
GOINSECURE=
GOMOD=/dev/null
GOPATH=/home/arsham/go:/usr/lib/go
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOROOT=/usr/lib/go


gopls: 2020/08/11 11:26:29 go/packages.Load
    snapshot=0
    directory=/home/arsham/Projects/Go/github.com/xxx/yyyy
    query=[./... builtin]
    packages=32

gopls: 2020/08/11 11:26:29 go/packages.Load
    snapshot=0
    directory=
    query=[./ builtin]
    packages=4

gopls: 2020/08/11 11:26:29 go/packages.Load
    snapshot=0
    directory=/usr/lib/go/src
    query=[./... builtin]
    packages=584

gopls: 2020/08/11 11:26:32 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:33 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:34 Shutdown session
    shutdown_session=1

gopls: gopls: failed reading header line: EOF
gopls: 2020/08/11 11:26:34 Build info
----------
golang.org/x/tools/gopls 0.4.4
    golang.org/x/tools/gopls@v0.4.4 h1:8djGYsaZ0ByP0vaXg4T+mnyfDcHpWKSZ+tpQSGv9ahk=
    github.com/BurntSushi/toml@v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
    github.com/google/go-cmp@v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
    github.com/sergi/go-diff@v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
    golang.org/x/mod@v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
    golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
    golang.org/x/tools@v0.0.0-20200729181040-64cdafbe085c h1:jLQLIAedRoS9I2Py7l/ZAGGzUxLFsdg42JXEpS/a+ow=
    golang.org/x/xerrors@v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
    honnef.co/go/tools@v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
    mvdan.cc/gofumpt@v0.0.0-20200709182408-4fd085cb6d5f h1:gi7cb8HTDZ6q8VqsUpkdoFi3vxwHMneQ6+Q5Ap5hjPE=
    mvdan.cc/xurls/v2@v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A=

Go info
-------
go version go1.14.5 linux/amd64



gopls: 2020/08/11 11:26:34 go env for /home/arsham/Projects/Go/github.com/xxx/oooo
(root /home/arsham/Projects/Go/github.com/xxx/oooo)
(valid build configuration = true)
(build flags: [])
GOROOT=/usr/lib/go
GOFLAGS=-tags=integration
GOMOD=/home/arsham/Projects/Go/github.com/xxx/oooo/go.mod
GOMODCACHE=
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct
GOSUMDB=sum.golang.org
GOCACHE=/home/arsham/.cache/go-build
GOINSECURE=
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GO111MODULE=on


gopls: 2020/08/11 11:26:34 go env for /usr/lib/go/src
(root /usr/lib/go/src)
(valid build configuration = true)
(build flags: [])
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOROOT=/usr/lib/go
GOCACHE=/home/arsham/.cache/go-build
GOPATH=/home/arsham/go:/usr/lib/go
GOPROXY=https://proxy.golang.org,direct
GOSUMDB=sum.golang.org
GOFLAGS=-tags=integration
GOMOD=/usr/lib/go/src/go.mod
GOMODCACHE=
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GO111MODULE=on
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOINSECURE=


gopls: 2020/08/11 11:26:34 go env for /home/arsham/go/pkg/mod
(root )
(valid build configuration = false)
(build flags: [])
GOSUMDB=sum.golang.org
GOINSECURE=
GOMODCACHE=
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOCACHE=/home/arsham/.cache/go-build
GOFLAGS=-tags=integration
GOPROXY=https://proxy.golang.org,direct
GOROOT=/usr/lib/go
GOMOD=/dev/null
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GO111MODULE=on
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go


gopls: 2020/08/11 11:26:34 go/packages.Load
    snapshot=0
    directory=/home/arsham/Projects/Go/github.com/xxx/oooo
    query=[./... builtin]
    packages=6

gopls: 2020/08/11 11:26:34 go/packages.Load
    snapshot=0
    directory=
    query=[./ builtin]
    packages=4

gopls: 2020/08/11 11:26:35 go/packages.Load
    snapshot=0
    directory=/usr/lib/go/src
    query=[./... builtin]
    packages=584

gopls: gopls: failed reading header line: EOF
gopls: 2020/08/11 11:26:35 Shutdown session
    shutdown_session=1

gopls: 2020/08/11 11:26:35 server shutdown without initialization

gopls: gopls: failed reading header line: EOF
gopls: 2020/08/11 11:26:35 Shutdown session
    shutdown_session=1

gopls: 2020/08/11 11:26:35 server shutdown without initialization

gopls: 2020/08/11 11:26:35 Build info
----------
golang.org/x/tools/gopls 0.4.4
    golang.org/x/tools/gopls@v0.4.4 h1:8djGYsaZ0ByP0vaXg4T+mnyfDcHpWKSZ+tpQSGv9ahk=
    github.com/BurntSushi/toml@v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
    github.com/google/go-cmp@v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
    github.com/sergi/go-diff@v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
    golang.org/x/mod@v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
    golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
    golang.org/x/tools@v0.0.0-20200729181040-64cdafbe085c h1:jLQLIAedRoS9I2Py7l/ZAGGzUxLFsdg42JXEpS/a+ow=
    golang.org/x/xerrors@v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
    honnef.co/go/tools@v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
    mvdan.cc/gofumpt@v0.0.0-20200709182408-4fd085cb6d5f h1:gi7cb8HTDZ6q8VqsUpkdoFi3vxwHMneQ6+Q5Ap5hjPE=
    mvdan.cc/xurls/v2@v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A=

Go info
-------
go version go1.14.5 linux/amd64



gopls: 2020/08/11 11:26:36 server shutdown without initialization

gopls: 2020/08/11 11:26:36 Shutdown session
    shutdown_session=1

gopls: gopls: failed reading header line: EOF
gopls: 2020/08/11 11:26:36 go env for /home/arsham/Projects/Go/github.com/xxx/oooo
(root /home/arsham/Projects/Go/github.com/xxx/oooo)
(valid build configuration = true)
(build flags: [])
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOROOT=/usr/lib/go
GOMOD=/home/arsham/Projects/Go/github.com/xxx/oooo/go.mod
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GO111MODULE=on
GOCACHE=/home/arsham/.cache/go-build
GOMODCACHE=
GOSUMDB=sum.golang.org
GOFLAGS=-tags=integration
GOINSECURE=
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct


gopls: 2020/08/11 11:26:36 Build info
----------
golang.org/x/tools/gopls 0.4.4
    golang.org/x/tools/gopls@v0.4.4 h1:8djGYsaZ0ByP0vaXg4T+mnyfDcHpWKSZ+tpQSGv9ahk=
    github.com/BurntSushi/toml@v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
    github.com/google/go-cmp@v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
    github.com/sergi/go-diff@v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
    golang.org/x/mod@v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
    golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
    golang.org/x/tools@v0.0.0-20200729181040-64cdafbe085c h1:jLQLIAedRoS9I2Py7l/ZAGGzUxLFsdg42JXEpS/a+ow=
    golang.org/x/xerrors@v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
    honnef.co/go/tools@v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
    mvdan.cc/gofumpt@v0.0.0-20200709182408-4fd085cb6d5f h1:gi7cb8HTDZ6q8VqsUpkdoFi3vxwHMneQ6+Q5Ap5hjPE=
    mvdan.cc/xurls/v2@v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A=

Go info
-------
go version go1.14.5 linux/amd64



gopls: 2020/08/11 11:26:36 go env for /usr/lib/go/src
(root /usr/lib/go/src)
(valid build configuration = true)
(build flags: [])
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GO111MODULE=on
GOINSECURE=
GOMODCACHE=
GOPATH=/home/arsham/go:/usr/lib/go
GOROOT=/usr/lib/go
GOFLAGS=-tags=integration
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct
GOCACHE=/home/arsham/.cache/go-build
GOMOD=/usr/lib/go/src/go.mod
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOSUMDB=sum.golang.org


gopls: 2020/08/11 11:26:36 go env for /home/arsham/go/pkg/mod
(root )
(valid build configuration = false)
(build flags: [])
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GOSUMDB=sum.golang.org
GOFLAGS=-tags=integration
GOROOT=/usr/lib/go
GOMOD=/dev/null
GOMODCACHE=
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct
GO111MODULE=on
GOCACHE=/home/arsham/.cache/go-build
GOINSECURE=


gopls: 2020/08/11 11:26:36 go env for /home/arsham/Projects/Go/github.com/xxx/oooo
(root /home/arsham/Projects/Go/github.com/xxx/oooo)
(valid build configuration = true)
(build flags: [])
GOINSECURE=
GOROOT=/usr/lib/go
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GOSUMDB=sum.golang.org
GOMODCACHE=
GOPROXY=https://proxy.golang.org,direct
GO111MODULE=on
GOCACHE=/home/arsham/.cache/go-build
GOMOD=/home/arsham/Projects/Go/github.com/xxx/oooo/go.mod
GOFLAGS=-tags=integration
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz


gopls: 2020/08/11 11:26:36 go env for /usr/lib/go/src
(root /usr/lib/go/src)
(valid build configuration = true)
(build flags: [])
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GOROOT=/usr/lib/go
GOCACHE=/home/arsham/.cache/go-build
GOFLAGS=-tags=integration
GOMODCACHE=
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOPROXY=https://proxy.golang.org,direct
GOSUMDB=sum.golang.org
GO111MODULE=on
GOINSECURE=
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz
GOPATH=/home/arsham/go:/usr/lib/go
GOMOD=/usr/lib/go/src/go.mod


gopls: 2020/08/11 11:26:36 go env for /home/arsham/go/pkg/mod
(root )
(valid build configuration = false)
(build flags: [])
GOSUMDB=sum.golang.org
GOFLAGS=-tags=integration
GOMOD=/dev/null
GOMODCACHE=
GOROOT=/usr/lib/go
GOPROXY=https://proxy.golang.org,direct
GOPATH=/home/arsham/go:/usr/lib/go
GOINSECURE=
GONOPROXY=github.com/xxx/ttt,github.com/xxx/zzzz
GOPRIVATE=github.com/xxx/ttt,github.com/xxx/zzzz
GO111MODULE=on
GOCACHE=/home/arsham/.cache/go-build
GONOSUMDB=github.com/xxx/ttt,github.com/xxx/zzzz


gopls: 2020/08/11 11:26:36 go/packages.Load
    snapshot=0
    directory=/home/arsham/Projects/Go/github.com/xxx/oooo
    query=[./... builtin]
    packages=6

gopls: 2020/08/11 11:26:36 go/packages.Load
    snapshot=0
    directory=
    query=[./ builtin]
    packages=4

gopls: 2020/08/11 11:26:36 go/packages.Load
    snapshot=0
    directory=/home/arsham/Projects/Go/github.com/xxx/oooo
    query=[./... builtin]
    packages=6

gopls: 2020/08/11 11:26:36 go/packages.Load
    snapshot=0
    directory=
    query=[./ builtin]
    packages=4

gopls: 2020/08/11 11:26:37 go/packages.Load
    snapshot=0
    directory=/usr/lib/go/src
    query=[./... builtin]
    packages=584

gopls: 2020/08/11 11:26:37 go/packages.Load
    snapshot=0
    directory=/usr/lib/go/src
    query=[./... builtin]
    packages=584

gopls: 2020/08/11 11:26:38 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:39 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:40 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:41 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:41 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

gopls: 2020/08/11 11:26:41 go/packages.Load
    snapshot=0
    directory=
    query=[./]
    packages=3

```
</p>
</details>

Thank you.


Discussion:
I bisected the repo and it seems that 54b9adb3 commit introduced this bug. 5ce01a65 would be the last commit that doesn't have this issue. I hope that helps.
I restarted LSP servers two times after a fresh start. The first time give these logs:

```
Traceback (most recent call last):
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 1385, in run_
    return self.run(edit)
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/core/registry.py", line 129, in run
    windows.lookup(window).restart_sessions_async()
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/core/windows.py", line 327, in restart_sessions_async
    self.end_sessions_async()
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/core/windows.py", line 333, in end_sessions_async
    session.end_async()
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/core/sessions.py", line 837, in end_async
    sv.shutdown_async()
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/session_view.py", line 104, in shutdown_async
    listener.on_session_shutdown_async(self.session)
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 178, in on_session_shutdown_async
    self._text_change_listener.detach()
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 112, in detach
    self.remove()
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 1477, in remove
    sublime_api.buffer_clear_text_listener(self.__key)
TypeError: Integer required
```

And the second time:
```
Traceback (most recent call last):
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/core/sessions.py", line 854, in run_async
    mgr.on_post_exit_async(self, exit_code, exception)
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/core/windows.py", line 357, in on_post_exit_async
    listener.on_session_shutdown_async(session)
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 178, in on_session_shutdown_async
    self._text_change_listener.detach()
  File "/home/arsham/.config/sublime-text-3/Packages/LSP/plugin/documents.py", line 112, in detach
    self.remove()
  File "/opt/sublime_text/Lib/python33/sublime_plugin.py", line 1477, in remove
    sublime_api.buffer_clear_text_listener(self.__key)
TypeError: Integer required
```
Those errors are unrelated to the problem, but I can reproduce your issue and it just needs to be looked at. I guess when switching the project we are more aggressive with killing the server and it doesn't like that.
With the latest changes in the `st4000-exploration` branch (not released at the time of writing), the high CPU issue should no longer reproduce.

The error dialog will still be shown or not, depending on if you switch/close the project. The server is basically crashing in either case but in case of switching the project, our WindowManager is not destroyed so it handles the exception and shows the error dialog. When just closing the window the WindowManager is already gone so doesn't show the error.

Now just need to figure out if it crashes because of us or its a gopls bug...
~~Actually the server doesn't crash. It exits cleanly but our code is handling that wrongly.~~

EDIT: Actually it is crashing (returning with non-0 exit code) but only when we asked it to exit so it might be better to not propagate that error.
Thank you for the information. I will test the changes one you released and will let you know.
I'd like to "handle" this issue with crash dialog by ignoring any "crashes" that happen on explicit shutdown of the server (so when switching projects, closing the last file that uses the server or using "restart server" command). Only unexpected errors that happen during normal operation should be reported. I think that would be a good experience overall as the user shouldn't care about crashes in those former situations.

@rwols do you agree?

The gopls returning non-0 exit code is a gopls bug, I believe. I've reported it as https://github.com/golang/go/issues/40832
> @rwols do you agree?

Ignoring the exit code when shutting down on purpose seems reasonable to me, yes.
I can confirm that this issue is been fixed in 3c49f5f55683ca19796bf.

Thank you.
Not fully, the high CPU usage is fixed but the error dialog will still trigger on switching project.
It could be considered a separate issue but I think we can keep it open for a little longer. I have a fix for that too.

Resolving patch:
diff --git a/plugin/core/sessions.py b/plugin/core/sessions.py
--- a/plugin/core/sessions.py
+++ b/plugin/core/sessions.py
@@ -480,7 +480,7 @@ def __init__(self, manager: Manager, logger: Logger, workspace_folders: List[Wor
         self.capabilities = DottedDict()
         self.exiting = False
         self._init_callback = None  # type: Optional[InitCallback]
-        self._init_error = None  # type: Optional[Tuple[int, Exception]]
+        self._exit_result = None  # type: Optional[Tuple[int, Optional[Exception]]]
         self._views_opened = 0
         self._workspace_folders = workspace_folders
         self._session_views = WeakSet()  # type: WeakSet[SessionViewProtocol]
@@ -662,7 +662,7 @@ def _handle_initialize_success(self, result: Any) -> None:
             self._init_callback = None
 
     def _handle_initialize_error(self, result: Any) -> None:
-        self._init_error = (result.get('code', -1), Exception(result.get('message', 'Error initializing server')))
+        self._exit_result = (result.get('code', -1), Exception(result.get('message', 'Error initializing server')))
         # Init callback called after transport is closed to avoid pre-mature GC of Session.
         self.end_async()
 
@@ -816,6 +816,11 @@ def _progress_string(self, token: Any, value: Dict[str, Any]) -> str:
 
     # --- shutdown dance -----------------------------------------------------------------------------------------------
 
+    def exit(self) -> None:
+        # exit() is only called when doing an explicit session shutdown. Ignore errors on exit then.
+        self._exit_result = (0, None)
+        super().exit()
+
     def end_async(self) -> None:
         # TODO: Ensure this function is called only from the async thread
         if self.exiting:
@@ -836,10 +841,9 @@ def on_transport_close(self, exit_code: int, exception: Optional[Exception]) ->
         self.state = ClientStates.STOPPING
         super().on_transport_close(exit_code, exception)
         self._response_handlers.clear()
-        if self._init_error:
-            init_code, init_exception = self._init_error
-            exit_code = init_code
-            exception = init_exception
+        if self._exit_result:
+            # Override potential exit error with a saved one.
+            exit_code, exception = self._exit_result
 
         def run_async() -> None:
             mgr = self.manager()


Test patch: