File: CrashRecoveryTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (319 lines) | stat: -rw-r--r-- 10,878 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import ISDBTestSupport
import LSPLogging
import LSPTestSupport
import LanguageServerProtocol
import SKSupport
import SKTestSupport
import SourceKitD
@_spi(Testing) import SourceKitLSP
import SwiftExtensions
import XCTest

import enum PackageLoading.Platform

fileprivate extension HoverResponse {
  func contains(string: String) -> Bool {
    switch self.contents {
    case .markedStrings(let markedStrings):
      for markedString in markedStrings {
        switch markedString {
        case .markdown(value: let value), .codeBlock(language: _, value: let value):
          if value.contains(string) {
            return true
          }
        }
      }
    case .markupContent(let markdownString):
      if markdownString.value.contains(string) {
        return true
      }
    }
    return false
  }
}

final class CrashRecoveryTests: XCTestCase {
  func testSourcekitdCrashRecovery() async throws {
    try SkipUnless.platformIsDarwin("Linux and Windows use in-process sourcekitd")
    try SkipUnless.longTestsEnabled()

    let testClient = try await TestSourceKitLSPClient(
      capabilities: ClientCapabilities(window: WindowClientCapabilities(workDoneProgress: true)),
      usePullDiagnostics: false
    )
    let uri = DocumentURI(for: .swift)

    let positions = testClient.openDocument(
      """
      func 1️⃣foo() {
        print("Hello world")
      }
      """,
      uri: uri
    )

    // Wait for diagnostics to be produced to make sure the document open got handled by sourcekitd.
    _ = try await testClient.nextDiagnosticsNotification()

    // Do a sanity check and verify that we get the expected result from a hover response before crashing sourcekitd.

    let hoverRequest = HoverRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
    let preCrashHoverResponse = try await testClient.send(hoverRequest)
    precondition(
      preCrashHoverResponse?.contains(string: "foo()") ?? false,
      "Sanity check failed. The Hover response did not contain foo(), even before crashing sourcekitd. Received response: \(String(describing: preCrashHoverResponse))"
    )

    testClient.handleSingleRequest { (request: CreateWorkDoneProgressRequest) -> VoidResponse in
      return VoidResponse()
    }

    // Crash sourcekitd

    let swiftLanguageService =
      await testClient.server.languageService(
        for: uri,
        .swift,
        in: testClient.server.workspaceForDocument(uri: uri)!
      ) as! SwiftLanguageService

    await swiftLanguageService.crash()

    let crashedNotification = try await testClient.nextNotification(ofType: WorkDoneProgress.self, timeout: .seconds(5))
    XCTAssertEqual(
      crashedNotification.value,
      .begin(
        WorkDoneProgressBegin(
          title: "SourceKit-LSP: Restoring functionality",
          message: "Please run 'sourcekit-lsp diagnose' to file an issue"
        )
      )
    )

    // sourcekitd's semantic request timer is only started when the first semantic request comes in.
    // Send a hover request (which will fail) to trigger that timer.
    // Afterwards wait for semantic functionality to be restored.
    _ = try? await testClient.send(hoverRequest)
    let semanticFunctionalityRestoredNotification = try await testClient.nextNotification(
      ofType: WorkDoneProgress.self,
      timeout: .seconds(30)
    )
    XCTAssertEqual(semanticFunctionalityRestoredNotification.value, .end(WorkDoneProgressEnd()))

    // Check that we get the same hover response from the restored in-memory state

    await assertNoThrow {
      let postCrashHoverResponse = try await testClient.send(hoverRequest)
      XCTAssertTrue(postCrashHoverResponse?.contains(string: "foo()") ?? false)
    }
  }

  private func crashClangd(for testClient: TestSourceKitLSPClient, document docUri: DocumentURI) async throws {
    let clangdServer = await testClient.server.languageService(
      for: docUri,
      .cpp,
      in: testClient.server.workspaceForDocument(uri: docUri)!
    )!

    let clangdCrashed = self.expectation(description: "clangd crashed")
    let clangdRestarted = self.expectation(description: "clangd restarted")

    await clangdServer.addStateChangeHandler { (oldState, newState) in
      switch newState {
      case .connectionInterrupted:
        clangdCrashed.fulfill()
      case .connected:
        clangdRestarted.fulfill()
      default:
        break
      }
    }

    await clangdServer.crash()

    try await fulfillmentOfOrThrow([clangdCrashed])
    try await fulfillmentOfOrThrow([clangdRestarted])
  }

  func testClangdCrashRecovery() async throws {
    try SkipUnless.longTestsEnabled()

    let testClient = try await TestSourceKitLSPClient()
    let uri = DocumentURI(for: .cpp)

    let positions = testClient.openDocument("1️⃣", uri: uri)

    // Make a change to the file that's not saved to disk. This way we can check that we re-open the correct in-memory state.

    let addFuncChange = TextDocumentContentChangeEvent(
      range: Range(positions["1️⃣"]),
      rangeLength: 0,
      text: """

        void main() {
        }
        """
    )

    testClient.send(
      DidChangeTextDocumentNotification(
        textDocument: VersionedTextDocumentIdentifier(uri, version: 2),
        contentChanges: [addFuncChange]
      )
    )

    // Do a sanity check and verify that we get the expected result from a hover response before crashing clangd.

    let expectedHoverRange = Position(line: 1, utf16index: 5)..<Position(line: 1, utf16index: 9)

    let hoverRequest = HoverRequest(
      textDocument: TextDocumentIdentifier(uri),
      position: Position(line: 1, utf16index: 6)
    )
    let preCrashHoverResponse = try await testClient.send(hoverRequest)
    precondition(
      preCrashHoverResponse?.range == expectedHoverRange,
      "Sanity check failed. The Hover response was not what we expected, even before crashing sourcekitd"
    )

    // Crash clangd

    try await crashClangd(for: testClient, document: uri)

    // Check that we have re-opened the document with the correct in-memory state

    await assertNoThrow {
      let postCrashHoverResponse = try await testClient.send(hoverRequest)
      XCTAssertEqual(postCrashHoverResponse?.range, expectedHoverRange)
    }
  }

  func testClangdCrashRecoveryReopensWithCorrectBuildSettings() async throws {
    try SkipUnless.longTestsEnabled()

    let project = try await MultiFileTestProject(files: [
      "main.cpp": """
      #if FOO
      void 1️⃣foo2️⃣() {}
      #else
      void foo() {}
      #endif

      int main() {
        3️⃣foo4️⃣();
      }
      """,
      "compile_flags.txt": """
      -DFOO
      """,
    ])

    let (mainUri, positions) = try project.openDocument("main.cpp")

    // Do a sanity check and verify that we get the expected result from a hover response before crashing clangd.

    let expectedHighlightResponse = [
      DocumentHighlight(range: positions["1️⃣"]..<positions["2️⃣"], kind: .text),
      DocumentHighlight(range: positions["3️⃣"]..<positions["4️⃣"], kind: .text),
    ]

    let highlightRequest = DocumentHighlightRequest(
      textDocument: TextDocumentIdentifier(mainUri),
      position: positions["3️⃣"]
    )
    let preCrashHighlightResponse = try await project.testClient.send(highlightRequest)
    precondition(
      preCrashHighlightResponse == expectedHighlightResponse,
      "Sanity check failed. The Hover response was not what we expected, even before crashing sourcekitd"
    )

    // Crash clangd

    try await crashClangd(for: project.testClient, document: mainUri)

    // Check that we have re-opened the document with the correct build settings
    // If we did not recover the correct build settings, document highlight would
    // pick the definition of foo() in the #else branch.

    await assertNoThrow {
      let postCrashHighlightResponse = try await project.testClient.send(highlightRequest)
      XCTAssertEqual(postCrashHighlightResponse, expectedHighlightResponse)
    }
  }

  func testPreventClangdCrashLoop() async throws {
    try SkipUnless.longTestsEnabled()

    let testClient = try await TestSourceKitLSPClient()
    let uri = DocumentURI(for: .cpp)

    let positions = testClient.openDocument("1️⃣", uri: uri)

    // Send a nonsensical request to wait for clangd to start up

    let hoverRequest = HoverRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
    _ = try await testClient.send(hoverRequest)

    // Keep track of clangd crashes

    let clangdServer = await testClient.server.languageService(
      for: uri,
      .cpp,
      in: testClient.server.workspaceForDocument(uri: uri)!
    )!

    let clangdCrashed = self.expectation(description: "clangd crashed")
    clangdCrashed.assertForOverFulfill = false

    let clangdRestartedFirstTime = self.expectation(description: "clangd restarted for the first time")
    let clangdRestartedSecondTime = self.expectation(description: "clangd restarted for the second time")

    let clangdHasRestartedFirstTime = ThreadSafeBox(initialValue: false)

    await clangdServer.addStateChangeHandler { (oldState, newState) in
      switch newState {
      case .connectionInterrupted:
        clangdCrashed.fulfill()
      case .connected:
        clangdHasRestartedFirstTime.withLock { clangdHasRestartedFirstTime in
          if !clangdHasRestartedFirstTime {
            clangdRestartedFirstTime.fulfill()
            clangdHasRestartedFirstTime = true
          } else {
            clangdRestartedSecondTime.fulfill()
          }
        }
      default:
        break
      }
    }

    await clangdServer.crash()

    try await fulfillmentOfOrThrow([clangdCrashed], timeout: 5)
    try await fulfillmentOfOrThrow([clangdRestartedFirstTime], timeout: 30)
    // Clangd has restarted. Note the date so we can check that the second restart doesn't happen too quickly.
    let firstRestartDate = Date()

    // Crash clangd again. This time, it should only restart after a delay.
    await clangdServer.crash()

    try await fulfillmentOfOrThrow([clangdRestartedSecondTime], timeout: 30)
    XCTAssert(
      Date().timeIntervalSince(firstRestartDate) > 5,
      "Clangd restarted too quickly after crashing twice in a row. We are not preventing crash loops."
    )
  }
}