Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Clear Diagnostics when file is closed #1591

Merged
merged 21 commits into from
Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
a0440fc
fix: LSP Change 'info' to 'hint' to eliminate noisy blue squiggles sh…
lovettchris Sep 12, 2022
b66b2a7
undo change to .hint for informational messages.
lovettchris Sep 13, 2022
ebb1e57
fix: CR feedback, move the exitWorker function.
lovettchris Sep 13, 2022
811c32d
fix: remove blank line
lovettchris Sep 13, 2022
9cdac72
Merge remote-tracking branch 'upstream/master' into clovett/clear_pro…
lovettchris Sep 19, 2022
1b98766
fix hang in the tests
lovettchris Sep 19, 2022
8f30109
fix: code review feedback.
lovettchris Sep 19, 2022
380728d
fix: add lspShutdown helper method that does the property handshake.
lovettchris Sep 20, 2022
85cfbda
fix: move shutdown code out of Communication.lean.
lovettchris Sep 23, 2022
c42a70b
fix: move clear diagnostics on file close to Watchdog.
lovettchris Sep 23, 2022
79c331b
Merge branch 'master' into clovett/clear_problems
lovettchris Sep 26, 2022
761460d
fix: revert unnecessary changes.
lovettchris Sep 26, 2022
665bf37
fix: use repeat instead of while True
lovettchris Sep 26, 2022
bde17e8
Merge branch 'master' into clovett/clear_problems
lovettchris Oct 4, 2022
3d27b26
fix: remove blank lines
lovettchris Oct 4, 2022
c9832a9
fix: fix race condition to ensure clearing of diagnostics is really a…
lovettchris Oct 4, 2022
36a531d
fix: ensure forwardMessages finds the updated WorkState.
lovettchris Oct 4, 2022
7ca3a41
fix: remove trace statement.
lovettchris Oct 4, 2022
8969ee8
fix: code review feedback.
lovettchris Oct 6, 2022
6f614a6
fix: code review - revert unneccesary edits.
lovettchris Oct 7, 2022
6d8b8a5
Merge branch 'master' into clovett/clear_problems
lovettchris Oct 7, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/Lean/Data/Lsp/Ipc.lean
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ def writeRequest (r : Request α) : IpcM Unit := do
def writeNotification (n : Notification α) : IpcM Unit := do
(←stdin).writeLspNotification n

def shutdown (requestNo : Nat) : IpcM Unit := do
let hIn ← stdout
let hOut ← stdin
hOut.writeLspRequest ⟨requestNo, "shutdown", Json.null⟩
repeat
let shutMsg ← hIn.readLspMessage
match shutMsg with
| Message.response id result =>
assert! result.isNull
if id != requestNo then
throw <| IO.userError s!"Expected id {requestNo}, got id {id}"

hOut.writeLspNotification ⟨"exit", Json.null⟩
break
| _ => -- ignore other messages in between.
pure ()

def readMessage : IpcM JsonRpc.Message := do
(←stdout).readLspMessage

Expand Down
13 changes: 11 additions & 2 deletions src/Lean/Server/FileWorker.lean
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,16 @@ section MessageHandling
end MessageHandling

section MainLoop

/-- called when document is closed so we can clear any diagnostics and cancel pending work -/
def exitWorker : WorkerM Unit := do
let ctx ← read
let state ← get
let doc := state.doc
doc.cancelTk.set
-- this is acting like an acknowledgement back to the Watchdog that exit was in fact received.
publishDiagnostics doc.meta #[] ctx.hOut
lovettchris marked this conversation as resolved.
Show resolved Hide resolved

partial def mainLoop : WorkerM Unit := do
let ctx ← read
let mut st ← get
Expand Down Expand Up @@ -449,8 +459,7 @@ section MainLoop
handleRequest id method (toJson params)
mainLoop
| Message.notification "exit" none =>
let doc := (←get).doc
doc.cancelTk.set
exitWorker
lovettchris marked this conversation as resolved.
Show resolved Hide resolved
return ()
| Message.notification method (some params) =>
handleNotification method (toJson params)
Expand Down
32 changes: 24 additions & 8 deletions src/Lean/Server/Watchdog.lean
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ section Utils
worker arrives. -/
| crashed (queuedMsgs : Array JsonRpc.Message)
| running
| exiting

abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare

Expand All @@ -123,7 +124,7 @@ section FileWorker
doc : OpenDocument
proc : Process.Child workerCfg
commTask : Task WorkerEvent
state : WorkerState
state : IO.Ref WorkerState
-- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state
/-- The pending requests map contains all requests
that have been received from the LSP client, but were not answered yet.
Expand Down Expand Up @@ -224,7 +225,8 @@ section ServerM
/-- Creates a Task which forwards a worker's messages into the output stream until an event
which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/
private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do
let o := (←read).hOut
let ctx ← read
let o := ctx.hOut
let rec loop : ServerM WorkerEvent := do
try
let msg ← fw.stdout.readLspMessage
Expand All @@ -246,14 +248,26 @@ section ServerM
if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then
handleIleanInfoFinal fw params
| _ => o.writeLspMessage msg

match (← fw.state.get) with
| .exiting =>
-- the above may have just sent the response to the "exit" command,
-- and now we ensure that clear diagnostics is the last thing we should do
-- so we never leave stale diagnostics around for this file.
let meta := fw.doc.meta
dbg_trace "sending clear diagnostics from Watchdog!"
publishDiagnostics meta #[] o
return WorkerEvent.terminated
| _ => pure

catch err =>
-- If writeLspMessage from above errors we will block here, but the main task will
-- quit eventually anyways if that happens
let exitCode ← fw.proc.wait
if exitCode = 0 then
-- Worker was terminated
fw.errorPendingRequests o ErrorCode.contentModified
("The file worker has been terminated. Either the header has changed,"
(s!"The file worker for {fw.doc.meta.uri} has been terminated. Either the header has changed,"
++ " or the file was closed, or the server is shutting down.")
return WorkerEvent.terminated
else
Expand All @@ -263,6 +277,7 @@ section ServerM
publishProgressAtPos fw.doc.meta 0 o (kind := LeanFileProgressKind.fatalError)
return WorkerEvent.crashed err
loop

let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated
return task.map fun
| Except.ok ev => ev
Expand All @@ -283,7 +298,7 @@ section ServerM
doc := ⟨m, headerAst⟩
proc := workerProc
commTask := Task.pure WorkerEvent.terminated
state := WorkerState.running
state := ← IO.mkRef WorkerState.running
pendingRequestsRef := pendingRequestsRef
groupedEditsRef := ← IO.mkRef none
}
Expand All @@ -306,6 +321,7 @@ section ServerM
def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do
let fw ← findFileWorker! uri
try
fw.state.modify (λ _ => WorkerState.exiting)
fw.stdin.writeLspMessage (Message.notification "exit" none)
catch _ =>
/- The file worker must have crashed just when we were about to terminate it!
Expand All @@ -318,7 +334,7 @@ section ServerM
eraseFileWorker uri

def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do
updateFileWorkers { ←findFileWorker! uri with state := WorkerState.crashed queuedMsgs }
(←findFileWorker! uri).state.modify (λ _ => WorkerState.crashed queuedMsgs)

/-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed
and restarts the file worker if the `crashed` flag was already set. Just logs an error if there
Expand All @@ -336,7 +352,7 @@ section ServerM
| none => (false, none)
if pendingEdit then
return
match fw.state with
match (← fw.state.get) with
| WorkerState.crashed queuedMsgs =>
let mut queuedMsgs := queuedMsgs
if queueFailedMessage then
Expand All @@ -356,7 +372,7 @@ section ServerM
crashedMsgs := crashedMsgs.push msg
if ¬ crashedMsgs.isEmpty then
handleCrash uri crashedMsgs
| WorkerState.running =>
| _ =>
let initialQueuedMsgs :=
if queueFailedMessage then
#[msg]
Expand Down Expand Up @@ -587,7 +603,7 @@ section MainLoop
let workers ← st.fileWorkersRef.get
let mut workerTasks := #[]
for (_, fw) in workers do
if let WorkerState.running := fw.state then
if let WorkerState.running := (← fw.state.get) then
workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)
if let some ge ← fw.groupedEditsRef.get then
workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw)
Expand Down
6 changes: 2 additions & 4 deletions tests/lean/interactive/run.lean
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,6 @@ partial def main (args : List String) : IO Unit := do
| _ =>
lastActualLineNo := lineNo
lineNo := lineNo + 1
Ipc.writeRequest ⟨requestNo, "shutdown", Json.null⟩
let shutResp ← Ipc.readResponseAs requestNo Json
assert! shutResp.result.isNull
Ipc.writeNotification ⟨"exit", Json.null⟩

Ipc.shutdown requestNo
discard <| Ipc.waitForExit
5 changes: 1 addition & 4 deletions tests/lean/server/diags.lean
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,5 @@ def main : IO Unit := do
else
throw $ userError "Failed parsing test file."

Ipc.writeRequest ⟨2, "shutdown", Json.null⟩
let shutResp ← Ipc.readResponseAs 2 Json
assert! shutResp.result.isNull
Ipc.writeNotification ⟨"exit", Json.null⟩
Ipc.shutdown 2
discard $ Ipc.waitForExit
5 changes: 1 addition & 4 deletions tests/lean/server/edits.lean
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,5 @@ def main : IO Unit := do
else
throw $ userError "Failed parsing test file."

Ipc.writeRequest ⟨3, "shutdown", Json.null⟩
let shutResp ← Ipc.readResponseAs 3 Json
assert! shutResp.result.isNull
Ipc.writeNotification ⟨"exit", Json.null⟩
Ipc.shutdown 3
discard $ Ipc.waitForExit
7 changes: 2 additions & 5 deletions tests/lean/server/init_exit.lean
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ def main : IO Unit := do
hIn.flush
let initResp ← Ipc.readResponseAs 0 InitializeResult
let regWatchReq ← Ipc.readRequestAs "client/registerCapability" Json
Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩
Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩

Ipc.writeRequest ⟨1, "shutdown", Json.null⟩
let shutdownResp ← Ipc.readResponseAs 1 Json
assert! shutdownResp.result.isNull
Ipc.writeNotification ⟨"exit", Json.null⟩
Ipc.shutdown 1
discard Ipc.waitForExit