Skip to content

Close RPC sessions on server restart. - #66

Merged
gebner merged 18 commits into
masterfrom
close_sessions_on_server_restart
Nov 8, 2021
Merged

gebner merged 18 commits into
masterfrom
close_sessions_on_server_restart

Conversation

@gebner

@gebner gebner commented Nov 1, 2021 •

Copy link
Copy Markdown
Member

Fixes #52.

@lovettchris

Copy link
Copy Markdown

Cool, does this fix issue #58 ?

@lovettchris
lovettchris self-requested a review November 1, 2021 17:12
Comment thread vscode-lean4/src/infoview.ts Resolved
@Vtec234

Vtec234 commented Nov 1, 2021

Copy link
Copy Markdown
Member

I believe this is intended to fix a different issue, namely the one where RPC sessions are not closed on server restart -- see Zulip. However this is not the right fix. The issue seems to be that:

  • either the infoview is not reinitialized, i.e. somehow clear() in infoview.ts doesn't work; or
  • the infoview is reinitialized correctly, and an RPC session for B.lean starts but B is not opened in the server (?!); or
  • something else is going on.

@lovettchris

lovettchris commented Nov 2, 2021 •

Copy link
Copy Markdown

I believe this is intended to fix a different issue, namely the one where RPC sessions are not closed on server restart -- see Zulip. However this is not the right fix. The issue seems to be that:

  • either the infoview is not reinitialized, i.e. somehow clear() in infoview.ts doesn't work; or
  • the infoview is reinitialized correctly, and an RPC session for B.lean starts but B is not opened in the server (?!); or
  • something else is going on.

I put some console.logging in RpcSession constructor then replayed the scenario of opening 2 files, restarting the server then switching the files and the log output shows the expected RpcSessions are created and each rpc call is passing the correct document Uri:

    child process exited with code 0
    client starting
    client running
[opening first file named Mymath.lean]
    Creating new RpcSession id 12972191147399796795 for document    
        file:///d%3A/Temp/lean_examples/MyMath/MyMath.lean
[opening second file named util.lean]
    Creating new RpcSession id 2205546381138363094 for document         
        file:///d%3A/Temp/lean_examples/MyMath/MyMath/util.lean
[restarting the server]
    client has stopped or it failed to start
    client starting
    client running
    Creating new RpcSession id 12904032966990033144 for document         
        file:///d%3A/Temp/lean_examples/MyMath/MyMath/util.lean
[select second file]
    rejected promise not handled within 1 second: Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    Creating new RpcSession id 18268304082738162278 for document         
        file:///d%3A/Temp/lean_examples/MyMath/MyMath.lean

@Vtec234

Vtec234 commented Nov 2, 2021

Copy link
Copy Markdown
Member

A print statement here is not triggered for me on server restart, so indeed it looks like clear() does not work. Notably the documentation for Webview.html states: This should be a complete, valid html document. Changing this property causes the webview to be reloaded. but it does not look like it is actually reloaded. @lovettchris is it working for you? It looks like a VSCode bug, likely dependent on the version.

@gebner

gebner commented Nov 2, 2021

Copy link
Copy Markdown
Member Author

From what I can tell the clear() indeed doesn't work. However if clear() worked, then the infoview would lose config, diagnostics, progress, position information when the server is restarted.

@lovettchris

Copy link
Copy Markdown

I found and fixed a related bug here: #69

@Vtec234

Vtec234 commented Nov 4, 2021 •

Copy link
Copy Markdown
Member

From what I can tell the clear() indeed doesn't work. However if clear() worked, then the infoview would lose config, diagnostics, progress, position information when the server is restarted.

We should send the diagnostics, progress and position on clear in the same way we already do on infoview startup. I am in favor of this solution because it is low effort - it will allow the infoview to assume that unless it had received a didClose, file workers stay open (although they may still restart). An alternative would be to send a fake didClose for all previously open files other than the active editors (the only ones which VSCode sends a didOpen for on restart, thus creating new workers), or the serverRestarted event you proposed. But again, I am in favour of just nuking and reiniting the infoview as on server restart there cannot possibly be state we may persist in the infoview anyway. A similar approach works reasonably well for the file workers in the server.

EDIT: I can't get the HTML resetting to work, but we can reset the React UI quite easily ourselves. I implemented this alternative in #70.

Comment thread vscode-lean4/src/infoview.ts Resolved
Comment thread vscode-lean4/src/infoview.ts Outdated
if (this.webviewPanel && this.client.initializeResult && window.activeTextEditor){
await this.webviewPanel.api.initialize(this.client.initializeResult, this.getLocation(window.activeTextEditor));
}
void this.webviewPanel?.api?.serverRestarted()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the void this.webviewPanel?.api?.serverRestarted() event should be fired before calling this.webviewPanel.api.initialize

@gebner

gebner commented Nov 4, 2021

Copy link
Copy Markdown
Member Author

I think the void this.webviewPanel?.api?.serverRestarted() event should be fired before calling this.webviewPanel.api.initialize

There were a few issues related to the message protocol that got in the way here. For example the initialize call is only supposed to be called a single time, otherwise we tell react to mount the infoview component multiple times (which apparently replaces the old one but I'm not sure if it cleans up all the event handlers). I think part of the issue was also that the WithDiagnosticsContext only updates on the publishDiagnostics notification, creating a race condition with the serverRestarted event. The infoview also requested interactive diagnostics for other files (in addition to the current one).

I have now refactored the code a bit so that the diagnostics/progress contexts are always created, even if there is no server connected. This prevents race conditions that are caused by react's asynchronous updating.

Since I was already refactoring the diagnostics context, I've also implemented #52.

there cannot possibly be state we may persist in the infoview anyway.

I think we want to persist all UI state, open details, pins, tactic state filters, etc. The intention is that you can restart the server frequently and easily in Lean 4.

[]
)

useEvent(ec.events.serverRestarted, () => sessions.ensureAllSessionsClosed())

@Vtec234 Vtec234 Nov 4, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of adding even more complexity to RpcSessions with #closed, why don't we leave it as-is, and instead call dispose(), then setSessions(new RpcSessions(ec)) here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not a bad idea! But I believe the closed flag will still be necessary to prevent references from the old session to be released.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes, unfortunately. But we should still make a new RpcSessions object to make sure the promise chain in connectAt does not make modifications to this after a server restart (I don't think this can happen, but then again I didn't think the bugs we've seen would happen either). In that case dispose does not need to clear out #connected/#connecting, just has to clear the timeouts and set #closed so the FinalizationRegistry stops sending releases.

@lovettchris

Copy link
Copy Markdown

I think we want to persist all UI state, open details, pins, tactic state filters, etc. The intention is that you can restart the server frequently and easily in Lean 4.

Thanks your new bits work really well, switching Lean server versions is now very smooth, and the bug I reported before is fixed, the new edits in the .lean file are being picked up and new diagnostics are being shown correctly.

Comment thread lean4-infoview/src/infoview/info.tsx Resolved
<EditorContext.Provider value={ec}>
<Main/>
</EditorContext.Provider>
</React.StrictMode>, uiElement)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice, much simpler!


// this.client.initializeResult can be null if the server failed to start.
if (this.client.initializeResult) {
await webviewPanel.api.initialize(this.client.initializeResult, this.getLocation(editor))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much nicer, separating out the this.client.initializeResult until the separate serverRestarted event makes a lot of sense.

Comment thread lean4-infoview/src/infoviewApi.ts Resolved
Comment thread vscode-lean4/src/infoview.ts Resolved
Comment thread vscode-lean4/src/infoview.ts Resolved
Comment thread lean4-infoview/src/infoview/contexts.ts Resolved

let allReq = undefined
if (sv.hasWidgetsV1()) {
if (sv?.hasWidgetsV1()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very minor, but I would use sv! here keeping in mind the invariant that the message UI is not rendered if sv === undefined.

[]
);

const serverInitializeResult = useEventResult(ec.events.serverRestarted);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If useEventResult were higher-order and taking a function that maps the event value, we could also use it for uri/events.changedCursorLocation above.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good suggestion! But there's no higher-order argument necessary, you can just do a ?.uri afterwards.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the higher-order version anyhow to reduce rerenders.


useEvent(ec.events.serverRestarted, () => {
sessions.dispose();
setSessions(new RpcSessions(ec));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this deal with the possibility that there could be some pending async calls to sendClientRequest or await sesh.call that could complete after the new RpcSessions has been created, then you could have competing async requests, etc... I'd feel better if RpcSessions had a this.disposed flag that each async completion checked and bailed if it is set to true.

@gebner gebner Nov 5, 2021 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. A lot of this code assumes that the #connected and #connecting maps stay the same (even though the RpcSessions object is recreated every time a session is created). I don't want to refactor this right now.

@gebner
gebner force-pushed the close_sessions_on_server_restart branch from 473b583 to db230fb Compare November 5, 2021 10:23
@gebner

gebner commented Nov 5, 2021

Copy link
Copy Markdown
Member Author

I've noticed something else that's a bit disturbing. We use a lot of these React context objects to capture notifications sent from the server. However this causes serious performance issues. It's obvious once you think of it:

<ProgressContext.Provider value={allProgress}>
  {ret}
</ProgressContext.Provider>

Whenever allProgress changes, everything in ret is being rerendered. At first I accidentally had <WithRpcSessions> inside of the ProgressContext.Provider, which apparently causes the RPC session to be reset every time the server updated the progress...

We need to replace all these providers by Events.

@Vtec234

Vtec234 commented Nov 5, 2021

Copy link
Copy Markdown
Member

Whenever allProgress changes, everything in ret is being rerendered. At first I accidentally had <WithRpcSessions> inside of the ProgressContext.Provider, which apparently causes the RPC session to be reset every time the server updated the progress...

Isn't the whole point of contexts that only children which useContext are rerendered when the context changes? WithRpcSessions does not use the progress context, so it shouldn't matter. Could it be that you're only testing in debug mode where React does more updates than necessary to test correctness?

@gebner

gebner commented Nov 5, 2021

Copy link
Copy Markdown
Member Author

Isn't the whole point of contexts that only children which useContext are rerendered when the context changes?

I don't know, I haven't found a precise description of when react will rerender the components or mount/unmount them. AFAICT by default <A value={x}><Foo/></A> will at least rerender Foo and all children when x changes (unless you explicitly opt out using memoization). Whether A is a provider or not does not make a difference here. It also doesn't matter whether it is a debug build or not.

Could it be that you're only testing in debug mode where React does more updates than necessary to test correctness?

Yes, and this is also recommended by react. But this doesn't mean we can ignore this. If the extension is sluggish to the point of being unusable in a development build, then it becomes hard to work on it.

@Vtec234

Vtec234 commented Nov 5, 2021

Copy link
Copy Markdown
Member

by default <A value={x}><Foo/></A> will at least rerender Foo and all children when x changes

I can confirm this happens in development mode. It is unfortunate, conceptually I would expect React to keep track of which children actually useContext and only render those, however..

At first I accidentally had inside of the ProgressContext.Provider, which apparently causes the RPC session to be reset every time the server updated the progress...

I am more worried about this. This sounds like a bug in our logic more than anything about React. The WithRpcSessions component should not be re-created every time it is re-rendered, in particular the RpcSessions state should be the same object across its lifetime. Is this still reproducible in the before-last commit?

@gebner

gebner commented Nov 5, 2021

Copy link
Copy Markdown
Member Author

by default <A value={x}><Foo/></A> will at least rerender Foo and all children when x changes

I can confirm this happens in development mode. It is unfortunate, conceptually I would expect React to keep track of which children actually useContext and only render those, however..

That's not what React does, and it's well documented. And to reiterate, it has nothing to do with useContext. It's also independent of development/production build. The dev build only enables some additional warnings, it doesn't change the whole semantics.

At first I accidentally had inside of the ProgressContext.Provider, which apparently causes the RPC session to be reset every time the server updated the progress...

I am more worried about this. This sounds like a bug in our logic more than anything about React. The WithRpcSessions component should not be re-created every time it is re-rendered, in particular the RpcSessions state should be the same object across its lifetime. Is this still reproducible in the before-last commit?

Oh sorry, false alarm! I tried my standard stress test: https://gist.github.com/gebner/523230aa3f95a1f40b92aee998494da6

What happened is that I first hovered around in an interactive diagnostic, and this flickers a lot. I was afraid that this happened because I inadvertently swapped the order of the providers so I tried swapping them back. Then I hovered in the expected type and everything was fine.

(Of course what actually happened (before and after the swapping) is that the interactive diagnostics are reloaded every time a publishDiagnostics notification arrives, but the expected type is only updated when you move the cursor or the line is still being processed.)

@Vtec234

Vtec234 commented Nov 5, 2021

Copy link
Copy Markdown
Member

That's not what React does, and it's well documented. And to reiterate, it has nothing to do with useContext. It's also independent of development/production build. The dev build only enables some additional warnings, it doesn't change the whole semantics.

I see. Per the docs, "Even if an ancestor uses React.memo or shouldComponentUpdate, a rerender will still happen starting at the component itself using useContext.". So our options are to memoize more components, or implement what I thought React should be doing ourselves with Events (as you suggest).


const [isPaused, setPaused, [uri, diags], _] = usePausableState(false, [uri0, diags0]);
const [isPaused, setPaused, [uri, diags, iDiags], _] = usePausableState(false, [uri0, diags0, iDiags0]);
if (isPaused) void iDiags()

@Vtec234 Vtec234 Nov 5, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this fetching diagnostics when paused? Should it not rather do so on !isPaused?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, iDiags is a thunk and the code above forces it when the component switches from !isPaused to isPaused. (It will also force it on every subsequent update when the component is paused, but those will be no-ops.)

The idea is that we don't need to load the diagnostics when the "all messages" view is closed and not paused. But when it switches to paused, we need to fetch them.

if (!diags0) diags0 = [];
const diags0 = dc.get(uri0) || [];

let iDiags0 = React.useMemo(() => lazy(async () => {

@Vtec234 Vtec234 Nov 5, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this is the right way to do this. Per React docs: "Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The memo is fine here. The lazy function is side effect-free, it only creates the thunk but does not execute it.

But maybe we should use useEffect for the iDiags() call below..

@Vtec234 Vtec234 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!! My takeaway is that we should rethink:

  • the state machine/internal logic in RpcSessions
  • the use of React contexts; Events used correctly may trigger fewer re-renders

@lovettchris

lovettchris commented Nov 5, 2021 •

Copy link
Copy Markdown

Thanks!! My takeaway is that we should rethink:

  • the state machine/internal logic in RpcSessions
  • the use of React contexts; Events used correctly may trigger fewer re-renders

Is this the right way to see a render count? When I 'run without debugging" I'm seeing 71 renders during startup, and 36 renders each time I type a character in the .lean file....which does seem a tad excessive...

    const rendersCountRef = React.useRef(0);
    rendersCountRef.current += 1;

    return (
    <ConfigContext.Provider value={config}>
        <VersionContext.Provider value={sv}>
            <WithRpcSessions>
                <WithLspDiagnosticsContext>
                    <ProgressContext.Provider value={allProgress}>
                        {ret}
                    </ProgressContext.Provider>
                </WithLspDiagnosticsContext>
            </WithRpcSessions>
        </VersionContext.Provider>
        <div>
        RendersCounter rendered <b>{rendersCountRef.current}</b>
        </div>
    </ConfigContext.Provider>

I also packaged the extension as a vsix built from command line and ran that and the increment is smaller, it increments by 18 on every edit in the .lean file. So this is probably the "non debug" number.

@lovettchris

Copy link
Copy Markdown

By the way, there is a ton of amazing discussion in this PR that I would have loved to capture in a Zulip discussion thread, I think it is time we created a vscode specific channel for these discussions in Zulip and I would love to continue this discussion even after this PR is done. I've been analyzing the React dependencies and it would be fun to continue this kind of discussion there to help get more shared understanding and to develop a roadmap towards simplification/optimization of this stuff...
image

@lovettchris

lovettchris commented Nov 6, 2021 •

Copy link
Copy Markdown

I think I found a bug:

  1. open a vscode folder and open a .lean file and ensure info view is visible
  2. close info view
  3. type Ctrl+Shift+Enter to reopen info view
  4. Infoview says Waiting for Lean server to start... forever...

I think the problem is that the infoview does need to send webviewPanel.api.serverRestarted event in this case. I've rigged up a fix in this commit (just ignore the render count debugging code, although that might be a fun thing to include as some optional debugging thing also).

@Vtec234

Vtec234 commented Nov 8, 2021

Copy link
Copy Markdown
Member

Is this the right way to see a render count? When I 'run without debugging" I'm seeing 71 renders during startup, and 36 renders each time I type a character in the .lean file....which does seem a tad excessive...

I think it is right, and I agree it sounds excessive to call all our render functions this many times. Although it really depends, e.g. if only the top-level component is rendered 36 times but the expensive-to-compute children are memoised and not re-rendered, then it might be fine -- we should probably useMemo more components in any case. But ideally even without memoisation there would be fewer redraws.

@gebner

gebner commented Nov 8, 2021

Copy link
Copy Markdown
Member Author

Is this the right way to see a render count? When I 'run without debugging" I'm seeing 71 renders during startup, and 36 renders each time I type a character in the .lean file....which does seem a tad excessive...

Yes. The numbers don't surprise me. I think this means that there are around 15 commands (def/...) below the cursor. The server sends 2 notifications for every processed command (publishDiagnostics and fileProgress) and we do a rerender for each one of them.

@gebner

gebner commented Nov 8, 2021 •

Copy link
Copy Markdown
Member Author

I'm not sure if this is a regression in this PR, but if I leave vscode running in the background for a few minutes (one minute is not enough), then I get the following message (in the infoview hover) when I come back:

Error: Cannot decode params in RPC call 'Lean.Widget.InteractiveDiagnostics.infoToInteractive({"p":"1"})'
RPC reference '1' is not valid

(I could reproduce this on master, so I've filed it as #73.)

@lovettchris

Copy link
Copy Markdown

(I could reproduce this on master, so I've filed it as #73.)

I've seen this also.

@gebner
gebner merged commit 21e1ce8 into master Nov 8, 2021
@gebner
gebner deleted the close_sessions_on_server_restart branch July 20, 2022 07:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use the new lineRange parameter of the interactive diagnostics command.

3 participants