Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 7 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ instead. API tests are not run by `npx hereby validate` without `--api`.
If as part of your change you edit tools, benchmarks, or other ancillary parts of the repository, you should instead run `npx hereby validate --all` to ensure *everything* is working correctly. This will
most accurately approximate the results of a full CI run.

## Go Concurrency Tests

Prefer `testing/synctest` over wall-clock sleeps, polling loops, or `time.After` watchdogs in in-memory concurrency tests.
Create the test's goroutines, channels, timers, and mocks inside `synctest.Test`, and use `synctest.Wait()` before asserting that work remains blocked.
Use the bubble's fake clock when testing deadlines or timer behavior; do not rely on elapsed wall time to distinguish slow execution from a deadlock.
Keep real-time waits where tests depend on external processes, real network I/O, or OS file-watcher events that synctest cannot control.

## Compiler Features, Fixes, and Tests

When fixing a bug or implementing a new feature, at least one minimal test case should always be added in advance to verify the fix.
Expand Down
85 changes: 37 additions & 48 deletions tsc/internal/api/session_completion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package api

import (
"testing"
"time"
"testing/synctest"

"github.com/microsoft/TypeScript/tsc/internal/api/requestfilesystem"
"github.com/microsoft/TypeScript/tsc/internal/bundled"
Expand Down Expand Up @@ -497,65 +497,54 @@ func TestCompletionWithSymbolsAndExistingImportDoesNotDeadlock(t *testing.T) {
t.Skip("bundled files are not embedded")
}

const fileName = "/home/projects/p/src/index.ts"
const content = "import { otherValue } from \"./export\";\nsomeV"
projectSession, _ := projecttestutil.Setup(map[string]any{
"/home/projects/p/tsconfig.json": `{ "compilerOptions": { "module": "esnext", "target": "esnext" } }`,
"/home/projects/p/src/export.ts": "export const otherValue = 0; export const someValue = 1;",
fileName: content,
})
defer projectSession.Close()
projectSession.Configure(lsutil.UserPreferences{
IncludeCompletionsForModuleExports: core.TSTrue,
IncludeCompletionsForImportStatements: core.TSTrue,
})
// Detect blocked goroutines rather than treating slow race builds as deadlocks.
synctest.Test(t, func(t *testing.T) {
const fileName = "/home/projects/p/src/index.ts"
const content = "import { otherValue } from \"./export\";\nsomeV"
projectSession, _ := projecttestutil.Setup(map[string]any{
"/home/projects/p/tsconfig.json": `{ "compilerOptions": { "module": "esnext", "target": "esnext" } }`,
"/home/projects/p/src/export.ts": "export const otherValue = 0; export const someValue = 1;",
fileName: content,
})
defer projectSession.Close()
projectSession.Configure(lsutil.UserPreferences{
IncludeCompletionsForModuleExports: core.TSTrue,
IncludeCompletionsForImportStatements: core.TSTrue,
})

session := NewLSPSession(projectSession, nil)
defer session.Close()
session := NewLSPSession(projectSession, nil)
defer session.Close()

snapshotResp, err := session.handleCreateSnapshot(t.Context(), &CreateSnapshotParams{
OpenFiles: []DocumentIdentifier{{FileName: fileName}},
PrepareAutoImports: &DocumentIdentifier{FileName: fileName},
})
assert.NilError(t, err)
proj, err := session.handleGetDefaultProjectForFile(t.Context(), &GetDefaultProjectForFileParams{
Snapshot: snapshotResp.Snapshot,
File: DocumentIdentifier{FileName: fileName},
})
assert.NilError(t, err)
assert.Assert(t, proj != nil, "file should resolve to a default project")
snapshotResp, err := session.handleCreateSnapshot(t.Context(), &CreateSnapshotParams{
OpenFiles: []DocumentIdentifier{{FileName: fileName}},
PrepareAutoImports: &DocumentIdentifier{FileName: fileName},
})
assert.NilError(t, err)
proj, err := session.handleGetDefaultProjectForFile(t.Context(), &GetDefaultProjectForFileParams{
Snapshot: snapshotResp.Snapshot,
File: DocumentIdentifier{FileName: fileName},
})
assert.NilError(t, err)
assert.Assert(t, proj != nil, "file should resolve to a default project")

// IncludeSymbol pins completion to the single persistent API checker. When
// ranking the auto-import completion, the existing import makes the view
// consult that checker. This used to try to acquire the same checker again
// and deadlock.
type completionResult struct {
completions *CompletionInfoResponse
err error
}
result := make(chan completionResult, 1)
go func() {
completions, e := session.handleGetCompletionsAtPosition(t.Context(), &GetCompletionsAtPositionParams{
// IncludeSymbol pins completion to the single persistent API checker. When
// ranking the auto-import completion, the existing import makes the view
// consult that checker. This used to try to acquire the same checker again
// and deadlock.
completions, err := session.handleGetCompletionsAtPosition(t.Context(), &GetCompletionsAtPositionParams{
Snapshot: snapshotResp.Snapshot,
Project: proj.Handle,
File: DocumentIdentifier{FileName: fileName},
Position: uint32(len(content)),
IncludeSymbol: true,
})
result <- completionResult{completions: completions, err: e}
}()

select {
case completion := <-result:
assert.NilError(t, completion.err)
assert.Assert(t, completion.completions != nil, "expected a completion list")
for _, entry := range completion.completions.Entries {
assert.NilError(t, err)
assert.Assert(t, completions != nil, "expected a completion list")
for _, entry := range completions.Entries {
if entry.Name == "someValue" {
return
}
}
t.Fatal("expected auto-import completion for someValue")
case <-time.After(10 * time.Second):
t.Fatal("completion request deadlocked while examining an existing import")
}
})
}
89 changes: 43 additions & 46 deletions tsc/internal/contentmapper/host_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"sync"
"sync/atomic"
"testing"
"time"
"testing/synctest"

"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/contentmapper"
Expand Down Expand Up @@ -341,57 +341,54 @@ func TestRunnerTransformResponseValidation(t *testing.T) {

func TestHostClosesProcessWhenReadLoopFails(t *testing.T) {
t.Parallel()
closed := make(chan struct{}, 1)
spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) {
client, server := net.Pipe()
go func() {
defer server.Close()
protocol := ipc.NewJSONRPCProtocol(server)
message, err := protocol.ReadMessage()
assert.NilError(t, err)
assert.Equal(t, message.Method, contentmapper.MethodInitialize)
assert.NilError(t, protocol.WriteResponse(message.ID, contentmapper.InitializeResult{
PositionEncoding: contentmapper.PositionEncodingUTF8,
DiagnosticSource: "mapper",
}))
_, err = server.Write([]byte("oops\n"))
assert.NilError(t, err)
}()
return &closeSignalReadWriteCloser{ReadWriteCloser: client, closed: closed}, nil
synctest.Test(t, func(t *testing.T) {
closed := make(chan struct{}, 1)
spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) {
client, server := net.Pipe()
go func() {
defer server.Close()
protocol := ipc.NewJSONRPCProtocol(server)
message, err := protocol.ReadMessage()
assert.NilError(t, err)
assert.Equal(t, message.Method, contentmapper.MethodInitialize)
assert.NilError(t, protocol.WriteResponse(message.ID, contentmapper.InitializeResult{
PositionEncoding: contentmapper.PositionEncodingUTF8,
DiagnosticSource: "mapper",
}))
_, err = server.Write([]byte("oops\n"))
assert.NilError(t, err)
}()
return &closeSignalReadWriteCloser{ReadWriteCloser: client, closed: closed}, nil
})
host := contentmapper.NewHost(t.Context(), spawner, locale.Default)
defer host.Close()
mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}}
_, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""})
assert.Assert(t, err != nil)
<-closed
})
host := contentmapper.NewHost(t.Context(), spawner, locale.Default)
defer host.Close()
mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}}
_, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""})
assert.Assert(t, err != nil)
processClosed := false
select {
case <-closed:
processClosed = true
case <-time.After(time.Second):
processClosed = false
}
assert.Assert(t, processClosed, "mapper process was not closed after its read loop failed")
}

func TestHostReportsInitializationTimeoutBeforeClosingProcess(t *testing.T) {
t.Parallel()
spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) {
client, server := net.Pipe()
go func() {
defer server.Close()
_, _ = ipc.NewJSONRPCProtocol(server).ReadMessage()
<-t.Context().Done()
}()
return &exitOnCloseReadWriteCloser{ReadWriteCloser: client}, nil
synctest.Test(t, func(t *testing.T) {
spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) {
client, server := net.Pipe()
go func() {
defer server.Close()
_, _ = ipc.NewJSONRPCProtocol(server).ReadMessage()
<-t.Context().Done()
}()
return &exitOnCloseReadWriteCloser{ReadWriteCloser: client}, nil
})
host := contentmapper.NewHost(t.Context(), spawner, locale.Default)
defer host.Close()
mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}}
_, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""})
initializeError, ok := errors.AsType[*contentmapper.InitializeError](err)
assert.Assert(t, ok, "expected InitializeError, got %v", err)
assert.Equal(t, initializeError.Kind, contentmapper.InitializeErrorKindNoResponse)
})
host := contentmapper.NewHost(t.Context(), spawner, locale.Default)
defer host.Close()
mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}}
_, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""})
initializeError, ok := errors.AsType[*contentmapper.InitializeError](err)
assert.Assert(t, ok, "expected InitializeError, got %v", err)
assert.Equal(t, initializeError.Kind, contentmapper.InitializeErrorKindNoResponse)
}

func TestHostReportsProcessExitBeforeInitialization(t *testing.T) {
Expand Down
75 changes: 36 additions & 39 deletions tsc/internal/execute/build/graph_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"slices"
"strings"
"testing"
"time"
"testing/synctest"

"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/execute/build"
Expand Down Expand Up @@ -50,50 +50,47 @@ func TestBuildScheduling(t *testing.T) {
} {
t.Run(operation.name, func(t *testing.T) {
t.Parallel()
sys := newSchedulingTestSystem()
independentStarted := make(chan struct{})
sys.fs.onRead = func(path tspath.RootedFilePath) {
if path.BaseName() != "index.ts" {
return
}
switch path.Directory().BaseName() {
case "Leaf":
// Independent must start while Leaf is still occupying a builder.
select {
case <-independentStarted:
synctest.Test(t, func(t *testing.T) {
sys := newSchedulingTestSystem()
independentStarted := make(chan struct{})
sys.fs.onRead = func(path tspath.RootedFilePath) {
if path.BaseName() != "index.ts" {
return
case <-time.After(30 * time.Second):
t.Error("Independent was queued behind a builder waiting on Leaf")
}
case "Independent":
close(independentStarted)
switch path.Directory().BaseName() {
case "Leaf":
// Independent must start while Leaf is still occupying a builder.
<-independentStarted
case "Independent":
close(independentStarted)
}
}
}
command := tsoptions.ParseBuildCommandLine([]string{"--build", "--verbose", "--builders", "2", "Root", "Other"}, sys.FS(), sys.GetCurrentDirectory())
orchestrator := build.NewOrchestrator(build.Options{Sys: sys, Command: command})
var result *build.OrchestratorResult
if operation.refsOnly {
result = orchestrator.BuildReferences(t.Context(), operation.project)
} else {
result = orchestrator.Build(t.Context(), operation.project)
}
assert.Equal(t, result.Result.Status, tsc.ExitStatusSuccess)
assert.Equal(t, result.Statistics.Projects, len(operation.order))
assert.Equal(t, result.Statistics.ProjectsBuilt, len(operation.order))
reported := []string{}
for line := range strings.SplitSeq(sys.output.String(), "\n") {
if strings.Contains(line, "Building project") {
for _, project := range operation.order {
if strings.Contains(line, "'"+project+"/tsconfig.json'") {
reported = append(reported, project)
command := tsoptions.ParseBuildCommandLine([]string{"--build", "--verbose", "--builders", "2", "Root", "Other"}, sys.FS(), sys.GetCurrentDirectory())
orchestrator := build.NewOrchestrator(build.Options{Sys: sys, Command: command})
var result *build.OrchestratorResult
if operation.refsOnly {
result = orchestrator.BuildReferences(t.Context(), operation.project)
} else {
result = orchestrator.Build(t.Context(), operation.project)
}
assert.Equal(t, result.Result.Status, tsc.ExitStatusSuccess)
assert.Equal(t, result.Statistics.Projects, len(operation.order))
assert.Equal(t, result.Statistics.ProjectsBuilt, len(operation.order))
reported := []string{}
for line := range strings.SplitSeq(sys.output.String(), "\n") {
if strings.Contains(line, "Building project") {
for _, project := range operation.order {
if strings.Contains(line, "'"+project+"/tsconfig.json'") {
reported = append(reported, project)
}
}
}
}
}
assert.DeepEqual(t, reported, operation.order)
for _, project := range []string{"Leaf", "Middle", "Independent", "Root", "Other"} {
assert.Equal(t, sys.FS().FileExists(sys.GetCurrentDirectory().ResolveFile(project+"/dist/index.js")), slices.Contains(operation.order, project))
}
assert.DeepEqual(t, reported, operation.order)
for _, project := range []string{"Leaf", "Middle", "Independent", "Root", "Other"} {
assert.Equal(t, sys.FS().FileExists(sys.GetCurrentDirectory().ResolveFile(project+"/dist/index.js")), slices.Contains(operation.order, project))
}
})
})
}
}
Expand Down
Loading
Loading