robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
70.5 KiB2687 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
4local exec_lua = n.exec_lua
5
6-- TODO: test error message has correct stack trace when:
7-- task finishes with no continuation
8-- task finishes with synchronous wait
9-- nil in results
10
11-- TODO(lewis6991): test for cyclic await
12-- - child awaiting an ancestor (not allowed)
13-- - cyclic chain with detached tasks
14
15--- @param s string
16--- @param f fun(...)
17--- @param ... any
18local function it_exec(s, f, ...)
19  local args = { ... }
20  it(s, function()
21    exec_lua(f, unpack(args))
22  end)
23end
24
25describe('async', function()
26  before_each(function()
27    n.clear()
28    exec_lua('package.path = ...', package.path)
29
30    exec_lua(function()
31      _G.Async = require('vim.async')
32      _G.AsyncRuntime = require('vim.async._runtime')
33      local safe_pcall = pcall
34      local ok, coxpcall = pcall(require, 'coxpcall')
35      if ok and type(coxpcall) == 'table' and type(coxpcall.pcall) == 'function' then
36        safe_pcall = coxpcall.pcall
37      end
38      _G.pcall = safe_pcall
39      _G.await = Async.await
40      _G.run = Async.run
41      _G.wrap = Async.wrap
42      _G.uv_handles = setmetatable({}, { __mode = 'v' })
43
44      --- Keep track of uv handles so we can ensure they are closed
45      --- @generic T
46      --- @param name string
47      --- @param handle T?
48      --- @return T - ?
49      function _G.add_handle(name, handle)
50        uv_handles[name] = assert(handle)
51        return handle
52      end
53
54      --- Check task eventually completes with an error
55      --- @param task vim.async.Task
56      --- @param pat string
57      --- @return string
58      function _G.check_task_err(task, pat)
59        local ok, err = task:pwait(100)
60        if ok then
61          error('Expected task to error, but it completed successfully', 2)
62        elseif not (err:match('^' .. pat .. '$') or (pat == 'closed' and is_closed_error(err))) then
63          error('Unexpected error: ' .. tostring(task:traceback(err)), 2)
64        end
65        return err
66      end
67
68      --- @param s string
69      --- @return { [1]: string, pattern: boolean }
70      function _G.p(s)
71        return { s, pattern = true }
72      end
73
74      --- @param err any
75      --- @return boolean
76      function _G.is_closed_error(err)
77        return err == 'closed'
78          or (type(err) == 'string' and err:match('^closed\nstack traceback:') ~= nil)
79      end
80
81      --- @param err any
82      --- @return boolean
83      function _G.is_timeout_error(err)
84        return err == 'timeout'
85          or (type(err) == 'string' and err:match('^timeout\nstack traceback:') ~= nil)
86      end
87
88      function _G.is_jit()
89        return package.loaded.jit ~= nil
90      end
91
92      --- @param expected any
93      --- @param actual any
94      --- @param msg? string
95      function _G.eq(expected, actual, msg)
96        local match
97        if
98          type(expected) == 'table'
99          and type(expected[1]) == 'string'
100          and expected.pattern == true
101        then
102          match = actual:match(expected[1]) ~= nil
103          expected = expected[1]
104        else
105          match = vim.deep_equal(expected, actual)
106        end
107
108        if not match then
109          if type(actual) == 'string' then
110            actual = '\n│  ' .. actual:gsub('\n', '\n│  ')
111          else
112            actual = vim.inspect(actual)
113          end
114          if type(expected) == 'string' then
115            expected = '\n│  ' .. expected:gsub('\n', '\n│  ')
116          else
117            expected = vim.inspect(expected)
118          end
119          error(
120            ('%s\n\nactual: %s\n\nexpected: %s'):format(msg or 'Mismatch:', actual, expected),
121            2
122          )
123        end
124      end
125
126      --- @async~
127      function _G.eternity()
128        await(function(_cb)
129          -- Never call callback
130          return add_handle('timer', vim.uv.new_timer()) --[[@as vim.async.Closable]]
131        end)
132      end
133    end)
134  end)
135
136  after_each(function()
137    exec_lua(function()
138      for k, v in pairs(uv_handles) do
139        assert(v:is_closing(), ('uv handle %s is not closing'):format(k))
140      end
141      collectgarbage('collect')
142      assert(not next(uv_handles), 'Resources not collected')
143    end)
144  end)
145
146  describe('basic operations', function()
147    it_exec('can error stack trace on sync wait', function()
148      local task = run(function()
149        error('SYNC ERR')
150      end)
151      check_task_err(task, '.*async_spec.lua:%d+: SYNC ERR')
152    end)
153
154    it_exec('can await a uv callback function', function()
155      --- @param path string
156      --- @param options uv.spawn.options
157      --- @param on_exit fun(code: integer, signal: integer)
158      --- @return uv.uv_process_t handle
159      local function spawn(path, options, on_exit)
160        return add_handle('process', vim.uv.spawn(path, options, on_exit))
161      end
162
163      local done = run(function()
164        local code1 = await(3, spawn, 'echo', { args = { 'foo' } })
165        assert(code1 == 0)
166
167        local code2 = await(3, spawn, 'echo', { args = { 'bar' } })
168        assert(code2 == 0)
169        await(vim.schedule)
170
171        return true
172      end):wait(1000)
173
174      eq(true, done)
175    end)
176
177    it_exec('resumes sleep outside a fast event', function()
178      local in_fast_event = run(function()
179        Async.sleep(0)
180        return vim.in_fast_event()
181      end):wait(100)
182
183      eq(false, in_fast_event)
184    end)
185
186    it_exec('can await a run task', function()
187      local a = run(function()
188        return await(run(function()
189          await(vim.schedule)
190          return 'JJ'
191        end))
192      end):wait(10)
193
194      assert(a == 'JJ', 'GOT ' .. tostring(a))
195    end)
196
197    it_exec('can wait on an empty task', function()
198      local did_cb = false
199      local a = 1
200
201      local task = run(function()
202        -- task does not await anything, should complete immediately
203        a = a + 1
204      end)
205
206      task:on_complete(function()
207        did_cb = true
208      end) -- non-blocking
209
210      task:wait(100) -- blocking
211
212      assert(a == 2)
213      assert(did_cb)
214    end)
215
216    it_exec('on_complete observes a pending child task without starting it', function()
217      local results = {}
218
219      run(function()
220        local child = run(function()
221          results[#results + 1] = 'child_started'
222          return 'child_done'
223        end)
224
225        child:on_complete(function(err, value)
226          assert(not err, tostring(err))
227          results[#results + 1] = value
228        end)
229        results[#results + 1] = 'after_on_complete'
230      end):wait(100)
231
232      eq({
233        'after_on_complete',
234        'child_started',
235        'child_done',
236      }, results)
237    end)
238
239    it_exec('child tasks start when the parent reaches a checkpoint', function()
240      local results = {}
241
242      run(function()
243        run(function()
244          results[#results + 1] = 'child_started'
245        end)
246
247        results[#results + 1] = 'before_checkpoint'
248        await(vim.schedule)
249        results[#results + 1] = 'after_checkpoint'
250      end):wait(100)
251
252      eq({
253        'before_checkpoint',
254        'child_started',
255        'after_checkpoint',
256      }, results)
257    end)
258
259    it_exec('child tasks start at an explicit checkpoint', function()
260      local results = {}
261
262      run(function()
263        run(function()
264          results[#results + 1] = 'child_started'
265        end)
266
267        results[#results + 1] = 'before_checkpoint'
268        Async.checkpoint()
269        results[#results + 1] = 'after_checkpoint'
270      end):wait(100)
271
272      eq({
273        'before_checkpoint',
274        'child_started',
275        'after_checkpoint',
276      }, results)
277    end)
278
279    it_exec('handles tasks that complete', function()
280      local task = run(function()
281        -- should wait for 1 ms
282        await(function(callback)
283          local timer = add_handle('timer', vim.uv.new_timer())
284          timer:start(1, 0, callback)
285          return timer --[[@as vim.async.Closable]]
286        end)
287        await(vim.schedule)
288        return nil, 1
289      end)
290
291      local r1, r2 = task:wait(100)
292      eq(r1, nil)
293      eq(r2, 1)
294    end)
295
296    it_exec('can provide a traceback for nested tasks', function()
297      if not is_jit() then
298        return
299      end
300
301      --- @async
302      local function t1()
303        await(run(function()
304          error('GOT HERE')
305        end))
306      end
307
308      local task = run(function()
309        await(run(function()
310          await(run(function()
311            await(run(function()
312              t1()
313            end))
314          end))
315        end))
316      end)
317
318      local err = check_task_err(task, '.*async_spec.lua:%d+: GOT HERE')
319
320      local m = [[.*async_spec.lua:%d+: GOT HERE
321stack traceback:
322        %[thread: 0x%x+%] %[C%]: in function 'error'
323        %[thread: 0x%x+%] .*async_spec.lua:%d+: in function <.*async_spec.lua:%d+>
324        %[thread: 0x%x+%] .*async_spec.lua:%d+: in function 't1'
325        %[thread: 0x%x+%] .*async_spec.lua:%d+: in function <.*async_spec.lua:%d+>
326        %[thread: 0x%x+%] .*async_spec.lua:%d+: in function <.*async_spec.lua:%d+>
327        %[thread: 0x%x+%] .*async_spec.lua:%d+: in function <.*async_spec.lua:%d+>
328        %[thread: 0x%x+%] .*async_spec.lua:%d+: in function <.*async_spec.lua:%d+>]]
329
330      local tb = tostring(task:traceback(err) or ''):gsub('\t', '        ')
331      assert(tb:match(m), 'ERROR: ' .. tostring(tb))
332    end)
333
334    it_exec('does not keep completed awaited tasks in later tracebacks', function()
335      if not is_jit() then
336        return
337      end
338
339      for _, await_child in ipairs({
340        function()
341          await(run(function()
342            return 'done'
343          end))
344        end,
345        function()
346          local ok = Async.pawait(run(function()
347            error('child error')
348          end))
349          eq(false, ok)
350        end,
351      }) do
352        local task = run(function()
353          await_child()
354          error('parent error')
355        end)
356
357        local err = check_task_err(task, '.*async_spec.lua:%d+: parent error')
358        local tb = tostring(task:traceback(err) or '')
359
360        assert(tb:match("%[C%]: in function 'error'"), 'ERROR: ' .. tostring(tb))
361        assert(not tb:match('child error'), 'ERROR: ' .. tostring(tb))
362        assert(not tb:match('stack traceback:\nstack traceback:'), 'ERROR: ' .. tostring(tb))
363      end
364    end)
365
366    it_exec('does not print nil for tracebacks without a message', function()
367      if not is_jit() then
368        return
369      end
370
371      local task = run(function()
372        await(function() end)
373      end)
374
375      local tb = tostring(task:traceback() or '')
376      assert(not tb:match('^nil\n'), 'ERROR: ' .. tostring(tb))
377
378      task:close()
379      check_task_err(task, 'closed')
380    end)
381
382    it_exec('does not need new stack frame for non-deferred continuations', function()
383      --- @async
384      local function deep(n)
385        if n == 0 then
386          return 'done'
387        end
388        await(function(cb)
389          cb()
390        end)
391        return deep(n - 1)
392      end
393
394      local res = run(function()
395        return deep(10000)
396      end):wait()
397      assert(res == 'done')
398    end)
399
400    it_exec('does not retain unused run arguments after task starts', function()
401      local unused = {}
402      local weak = setmetatable({ unused }, { __mode = 'v' })
403
404      local task = run(function(_)
405        Async.sleep(100)
406      end, 'used', unused)
407
408      unused = nil
409      collectgarbage('collect')
410      collectgarbage('collect')
411
412      local retained = weak[1]
413      task:close()
414      check_task_err(task, 'closed')
415      eq(nil, retained)
416    end)
417  end)
418
419  describe('task cancellation and closing', function()
420    it_exec('can close tasks', function()
421      local task = run(eternity)
422      task:close()
423      check_task_err(task, 'closed')
424    end)
425
426    it_exec('can close tasks which waiting on a wrapped callback function', function()
427      local wfn = wrap(1, function(_callback)
428        return add_handle('timer', vim.uv.new_timer()) --[[@as vim.async.Closable]]
429      end)
430
431      local task = run(function()
432        wfn()
433      end)
434
435      task:close()
436      check_task_err(task, 'closed')
437    end)
438
439    it_exec('gracefully handles when closables are prematurely closed', function()
440      local result = run(function()
441        await(1, function(callback)
442          local timer = add_handle('timer', vim.uv.new_timer())
443          timer:close(callback)
444          return timer --[[@as vim.async.Closable]]
445        end)
446
447        return 'FINISH'
448      end):wait()
449
450      eq('FINISH', result)
451    end)
452
453    it_exec('callback function can be closed (nested)', function()
454      local child --- @type vim.async.Task
455      local task = run(function()
456        child = run(eternity)
457        await(child)
458      end)
459
460      task:close()
461
462      check_task_err(task, 'closed')
463      check_task_err(child, 'closed')
464    end)
465
466    it_exec('can timeout tasks', function()
467      local task = run(eternity)
468      check_task_err(task, 'timeout')
469      task:close()
470      check_task_err(task, 'closed')
471    end)
472
473    it_exec('can async timeout a test', function()
474      local task = run(eternity)
475      check_task_err(run(Async.timeout, 10, task), 'timeout')
476    end)
477
478    it_exec('timeout waits for target cleanup before raising timeout', function()
479      local cleanup_done = false
480
481      local task = run(function()
482        await(function()
483          return {
484            close = function(_, callback)
485              vim.schedule(function()
486                cleanup_done = true
487                callback()
488              end)
489            end,
490          }
491        end)
492      end)
493
494      check_task_err(run(Async.timeout, 1, task), 'timeout')
495      eq(true, cleanup_done)
496      check_task_err(task, 'closed')
497    end)
498
499    it_exec('timeout preserves target failure before the deadline', function()
500      local task = run(function()
501        Async.sleep(1)
502        error('TARGET_ERROR')
503      end)
504
505      check_task_err(run(Async.timeout, 100, task), '.*async_spec.lua:%d+: TARGET_ERROR')
506    end)
507
508    it_exec('returns when the task completes before the timeout', function()
509      local timeout_timer = {
510        closed = false,
511        close = function(self, callback)
512          self.closed = true
513          if callback then
514            callback()
515          end
516        end,
517        is_closing = function(self)
518          return self.closed
519        end,
520        start = function() end,
521      }
522
523      AsyncRuntime.config({
524        wait = vim.wait,
525        schedule = vim.schedule,
526        new_timer = function()
527          return timeout_timer
528        end,
529      })
530
531      local ok, err = pcall(function()
532        local task = run(function()
533          return 'FINISH'
534        end)
535        eq('FINISH', run(Async.timeout, 100, task):wait(10))
536        assert(timeout_timer.closed)
537      end)
538
539      AsyncRuntime.config({
540        wait = vim.wait,
541        schedule = vim.schedule,
542        new_timer = vim.uv.new_timer,
543      })
544      if not ok then
545        error(err, 0)
546      end
547    end)
548
549    it_exec('closes detached child tasks', function()
550      local task1 = run(eternity)
551      task1:close()
552
553      local task2 = run(function()
554        await(task1)
555      end)
556
557      check_task_err(task2, 'closed')
558    end)
559  end)
560
561  describe('error handling', function()
562    it_exec('handles tasks that error', function()
563      local task = run(function()
564        await(function(callback)
565          local timer = add_handle('timer', vim.uv.new_timer())
566          timer:start(1, 0, callback)
567          return timer --[[@as vim.async.Closable]]
568        end)
569        await(vim.schedule)
570        error('GOT HERE')
571      end)
572
573      check_task_err(task, '.*async_spec.lua:%d+: GOT HERE')
574    end)
575
576    it_exec('can handle errors in wrapped functions', function()
577      local task = run(function()
578        await(function(_callback)
579          error('ERROR')
580        end)
581      end)
582      check_task_err(task, '.*async_spec.lua:%d+: ERROR')
583    end)
584
585    it_exec('can pcall errors in wrapped functions', function()
586      local task = run(function()
587        return pcall(function()
588          await(function(_callback)
589            error('ERROR')
590          end)
591        end)
592      end)
593      local ok, msg = task:wait()
594      assert(not ok and msg, 'Expected error, got success')
595      assert(msg:match('^.*async_spec.lua:%d+: ERROR'), 'Got unexpected error: ' .. msg)
596    end)
597
598    it_exec('handles when a floating child errors', function()
599      local parent = run(function()
600        local _child = run(function(...)
601          Async.sleep(5)
602          error('CHILD ERROR')
603        end)
604      end)
605
606      check_task_err(parent, 'child error: .*async_spec.lua:%d+: CHILD ERROR')
607    end)
608
609    it_exec('handles when a floating child errors and parent errors', function()
610      local parent = run(function()
611        local _child = run(function(...)
612          Async.sleep(5)
613          error('CHILD ERROR')
614        end)
615        error('PARENT ERROR')
616      end)
617
618      check_task_err(parent, '.*async_spec.lua:%d+: PARENT ERROR')
619    end)
620  end)
621
622  describe('task iteration', function()
623    it_exec('can iterate detached tasks', function()
624      local tasks = {} --- @type vim.async.Task<any>[]
625      local expected = {} --- @type table[]
626
627      for i = 1, 10 do
628        tasks[i] = run(function()
629          if i % 2 == 0 then
630            await(vim.schedule)
631          end
632          return 'FINISH', i
633        end)
634        expected[i] = { 'FINISH', i }
635      end
636
637      local results = {} --- @type table[]
638      run(function()
639        local next_task = Async.iter(tasks)
640        while true do
641          local task = next_task()
642          if not task then
643            break
644          end
645          local r1, r2 = await(task)
646          results[r2] = { r1, r2 }
647        end
648      end):wait(1000)
649
650      eq(expected, results)
651    end)
652
653    it_exec('can inspect errors when iterating detached tasks', function()
654      local results = {} --- @type table[]
655      local tasks = {} --- @type vim.async.Task<any>[]
656      local task_err --- @type any
657
658      for i = 1, 10 do
659        tasks[i] = run(function()
660          await(vim.schedule)
661          if i == 3 then
662            error('ERROR IN TASK ' .. i)
663          end
664          return 'FINISH', i
665        end)
666      end
667
668      run(function()
669        local next_task = Async.iter(tasks)
670        while true do
671          local task = next_task()
672          if not task then
673            break
674          end
675          local ok, r1, r2 = Async.pawait(task)
676          if not ok then
677            task_err = r1
678            break
679          end
680          results[r2] = { r1, r2 }
681        end
682      end):wait(100)
683
684      --- @cast task_err string
685      assert(task_err:match('.*async_spec.lua:%d+: ERROR IN TASK 3'), task_err)
686
687      eq({
688        { 'FINISH', 1 },
689        { 'FINISH', 2 },
690      }, results)
691    end)
692
693    it_exec('iterates tasks in completion order', function()
694      --- @async
695      --- @param count integer
696      --- @param id integer
697      local function after_schedules(count, id)
698        for _ = 1, count do
699          await(vim.schedule)
700        end
701        return id
702      end
703
704      local tasks = {
705        run(after_schedules, 3, 1),
706        run(after_schedules, 1, 2),
707        run(after_schedules, 2, 3),
708      }
709
710      local order = {}
711      run(function()
712        local next_task = Async.iter(tasks)
713        while true do
714          local task = next_task()
715          if not task then
716            break
717          end
718          order[#order + 1] = await(task)
719        end
720      end):wait(100)
721
722      eq({ 2, 3, 1 }, order)
723    end)
724
725    it_exec('treats false task errors as errors when iterating', function()
726      local task = run(function()
727        await(vim.schedule)
728        error(false, 0)
729      end)
730
731      run(function()
732        local completed = Async.iter({ task })()
733        local ok, err = Async.pawait(completed)
734        eq(false, ok)
735        eq(false, err)
736      end):wait(100)
737    end)
738
739    it_exec('can iter tasks followed by error', function()
740      local task = run(function()
741        await(vim.schedule)
742        return 'FINISH', 1
743      end)
744
745      local expected = { { 'FINISH', 1 } }
746      local results = {} --- @type table[]
747
748      local task2 = run(function()
749        local next_task = Async.iter({ task })
750        while true do
751          local completed = next_task()
752          if not completed then
753            break
754          end
755          local r1, r2 = await(completed)
756          results[r2] = { r1, r2 }
757        end
758        error('GOT HERE')
759      end)
760
761      check_task_err(task2, '.*async_spec.lua:%d+: GOT HERE')
762      eq(expected, results)
763    end)
764
765    it_exec('can iter tasks with cancellation', function()
766      local tasks = {} --- @type vim.async.Task<any>[]
767
768      for i = 1, 4 do
769        tasks[i] = run(function()
770          if i == 2 then
771            eternity()
772          end
773          return 'FINISH', i
774        end)
775      end
776
777      assert(tasks[2]):close()
778
779      local results = {} --- @type table[]
780      local errs = {} --- @type any[]
781      run(function()
782        local next_task = Async.iter(tasks)
783        while true do
784          local task = next_task()
785          if not task then
786            break
787          end
788          local ok, r1, r2 = Async.pawait(task)
789          if ok then
790            results[r2] = { r1, r2 }
791          else
792            errs[#errs + 1] = r1
793          end
794        end
795      end):wait(100)
796
797      eq({
798        [1] = { 'FINISH', 1 },
799        [3] = { 'FINISH', 3 },
800        [4] = { 'FINISH', 4 },
801      }, results)
802      eq({ 'closed' }, errs)
803    end)
804
805    it_exec('can iter tasks with garbage collection', function()
806      --- @param task vim.async.Task
807      --- @return integer
808      local function get_task_callback_count(task)
809        --- @diagnostic disable-next-line: invisible
810        return vim.tbl_count(task._future._callbacks)
811      end
812
813      local task = run(eternity)
814
815      run(function()
816        local itr = Async.iter({ task })
817        eq(get_task_callback_count(task), 1, 'task should have one callback')
818        itr = nil
819        collectgarbage('collect')
820        eq(get_task_callback_count(task), 0, 'task should have no callbacks')
821      end):wait(100)
822
823      task:close()
824      check_task_err(task, 'closed')
825    end)
826
827    it_exec('handles empty task lists', function()
828      run(function()
829        eq(nil, Async.iter({})())
830      end):wait(100)
831    end)
832  end)
833
834  describe('child task management', function()
835    it_exec('does not close child tasks created outside of parent', function()
836      local t1 = run(Async.sleep, 10)
837      local t2 --- @type vim.async.Task
838      local t3 --- @type vim.async.Task
839
840      local parent = run(function()
841        t2 = run(Async.sleep, 10)
842        t3 = run(Async.sleep, 10):detach()
843        await(t1)
844      end)
845
846      parent:close()
847
848      check_task_err(parent, 'closed')
849      t1:wait()
850      check_task_err(t2, 'closed')
851      t3:wait()
852    end)
853
854    it_exec('stops observing external tasks when the waiter closes', function()
855      for _, wait in ipairs({ await, Async.pawait }) do
856        local external = run(eternity)
857        local waiter = run(function()
858          wait(external)
859        end)
860
861        waiter:close()
862        check_task_err(waiter, 'closed')
863
864        --- @diagnostic disable-next-line: invisible
865        local callback_count = vim.tbl_count(external._future._callbacks)
866        external:close()
867        check_task_err(external, 'closed')
868
869        eq(0, callback_count)
870      end
871    end)
872
873    it_exec('stops observing external tasks when a child fails', function()
874      for _, wait in ipairs({ await, Async.pawait }) do
875        local external = run(eternity)
876        local waiter = run(function()
877          run(function()
878            await(vim.schedule)
879            error('CHILD ERROR')
880          end)
881          wait(external)
882        end)
883
884        check_task_err(waiter, 'child error: .*async_spec.lua:%d+: CHILD ERROR')
885
886        --- @diagnostic disable-next-line: invisible
887        local callback_count = vim.tbl_count(external._future._callbacks)
888        external:close()
889        check_task_err(external, 'closed')
890
891        eq(0, callback_count)
892      end
893    end)
894
895    it_exec('stops observing children detached while being awaited', function()
896      for _, wait in ipairs({ await, Async.pawait }) do
897        local child --- @type vim.async.Task
898        local completions = 0
899        local parent = run(function()
900          child = run(eternity)
901          wait(child)
902        end)
903        parent:on_complete(function()
904          completions = completions + 1
905        end)
906
907        child:detach()
908        parent:close()
909        check_task_err(parent, 'closed')
910        eq(false, child:completed())
911
912        --- @diagnostic disable-next-line: invisible
913        local callback_count = vim.tbl_count(child._future._callbacks)
914        child:close()
915        check_task_err(child, 'closed')
916
917        eq(0, callback_count)
918        eq(1, completions)
919      end
920    end)
921
922    it_exec('ignores extra callback awaitable results', function()
923      for _, wait in ipairs({ await, Async.pawait }) do
924        local external = run(eternity)
925        local waiter = run(function()
926          wait(function()
927            return external, function()
928              error('EXTRA_RETURN_CALLED')
929            end
930          end)
931        end)
932
933        waiter:close()
934        check_task_err(waiter, 'closed')
935        external:close()
936        check_task_err(external, 'closed')
937      end
938    end)
939
940    it_exec('detached pending child starts independently', function()
941      local results = {}
942
943      run(function()
944        run(function()
945          results[#results + 1] = 'detached_started'
946        end):detach()
947
948        results[#results + 1] = 'parent_done'
949        await(vim.schedule)
950      end):wait(100)
951
952      eq({
953        'parent_done',
954        'detached_started',
955      }, results)
956    end)
957
958    it_exec('detached child failures do not fail the original parent', function()
959      local child --- @type vim.async.Task
960
961      local parent = run(function()
962        child = run(function()
963          await(vim.schedule)
964          error('DETACHED_ERROR')
965        end):detach()
966
967        await(vim.schedule)
968        return 'parent ok'
969      end)
970
971      eq('parent ok', parent:wait(100))
972      check_task_err(child, '.*async_spec.lua:%d+: DETACHED_ERROR')
973    end)
974
975    it_exec('attaches tasks created from synchronous callbacks inside a task', function()
976      local release --- @type fun()?
977      local results = {}
978
979      local parent = run(function()
980        local function call(callback)
981          callback()
982        end
983
984        call(function()
985          run(function()
986            await(function(callback)
987              release = callback
988            end)
989            results[#results + 1] = 'child_done'
990          end)
991        end)
992
993        results[#results + 1] = 'parent_body_done'
994      end)
995
996      local ok, err = parent:pwait(10)
997      eq(false, ok)
998      assert(is_timeout_error(err), 'Expected timeout, got: ' .. tostring(err))
999      eq({ 'parent_body_done' }, results)
1000      assert(release, 'attached child was not started at parent finish')
1001
1002      release()
1003      parent:wait(50)
1004
1005      eq({ 'parent_body_done', 'child_done' }, results)
1006    end)
1007
1008    it_exec('does not attach tasks created from event-loop callbacks', function()
1009      local release --- @type fun()?
1010      local child --- @type vim.async.Task
1011      local results = {}
1012
1013      local parent = run(function()
1014        await(function(callback)
1015          vim.schedule(function()
1016            child = run(function()
1017              await(function(child_callback)
1018                release = child_callback
1019              end)
1020              results[#results + 1] = 'child_done'
1021            end)
1022            callback()
1023          end)
1024        end)
1025
1026        results[#results + 1] = 'parent_done'
1027      end)
1028
1029      parent:wait(50)
1030
1031      eq({ 'parent_done' }, results)
1032      assert(child, 'event-loop callback did not create child task')
1033      assert(release, 'top-level callback task was not started')
1034
1035      release()
1036      child:wait(50)
1037
1038      eq({ 'parent_done', 'child_done' }, results)
1039    end)
1040
1041    it_exec('does not run pending children when parent errors before a checkpoint', function()
1042      local child --- @type vim.async.Task
1043      local child_ran = false
1044
1045      local parent = run(function()
1046        child = run(function()
1047          child_ran = true
1048        end)
1049
1050        error('PARENT_ERROR')
1051      end)
1052
1053      check_task_err(parent, '.*async_spec.lua:%d+: PARENT_ERROR')
1054      check_task_err(child, 'closed')
1055      eq(false, child_ran)
1056    end)
1057
1058    it_exec('synchronous child wait starts only the waited child', function()
1059      local results = {}
1060
1061      run(function()
1062        local child1 = run(function()
1063          results[#results + 1] = 'child1'
1064        end)
1065
1066        run(function()
1067          results[#results + 1] = 'child2'
1068        end)
1069
1070        child1:wait(100)
1071        eq({ 'child1' }, results)
1072      end):wait(100)
1073
1074      eq({ 'child1', 'child2' }, results)
1075    end)
1076
1077    it_exec('does not wait for detached task children after sync wait times out', function()
1078      local detached --- @type vim.async.Task
1079      local release --- @type fun()?
1080      local results = {}
1081
1082      local parent = run(function()
1083        await(vim.schedule)
1084
1085        detached = run(function()
1086          run(function()
1087            await(function(callback)
1088              release = callback
1089            end)
1090            results[#results + 1] = 'detached_child_done'
1091          end)
1092        end):detach()
1093
1094        local ok, err = detached:pwait(10)
1095        eq(false, ok)
1096        assert(is_timeout_error(err), 'Expected timeout, got: ' .. tostring(err))
1097
1098        results[#results + 1] = 'parent_done'
1099      end)
1100
1101      parent:wait(50)
1102
1103      eq({ 'parent_done' }, results)
1104      assert(release, 'detached child was not started')
1105
1106      release()
1107      detached:wait(50)
1108
1109      eq({ 'parent_done', 'detached_child_done' }, results)
1110    end)
1111
1112    it_exec('automatically awaits child tasks', function()
1113      local child1, child2 --- @type vim.async.Task, vim.async.Task
1114      local main = run(function()
1115        child1 = run(Async.sleep, 10)
1116        child2 = run(Async.sleep, 10)
1117      end)
1118
1119      main:wait()
1120      assert(child1:completed())
1121      assert(child2:completed())
1122    end)
1123
1124    it_exec('should not fail the parent task if children finish before parent', function()
1125      local release_parent --- @type fun()?
1126      local release_child1 --- @type fun()?
1127      local release_child2 --- @type fun()?
1128      local child1, child2 --- @type vim.async.Task, vim.async.Task
1129
1130      local main = run(function()
1131        child1 = run(function()
1132          await(function(callback)
1133            release_child1 = callback
1134          end)
1135        end)
1136        child2 = run(function()
1137          await(function(callback)
1138            release_child2 = callback
1139          end)
1140        end)
1141
1142        await(function(callback)
1143          release_parent = callback
1144        end)
1145      end)
1146
1147      assert(release_child1)
1148      assert(release_child2)
1149      assert(release_parent)
1150      release_child1()
1151      release_child2()
1152      assert(child1:completed())
1153      assert(child2:completed())
1154
1155      release_parent()
1156      main:wait()
1157    end)
1158
1159    it_exec('automatically closes suspended child tasks', function()
1160      local forever_child --- @type vim.async.Task
1161
1162      local main = run(function()
1163        forever_child = run(function()
1164          while true do
1165            Async.sleep(1)
1166          end
1167        end)
1168        Async.sleep(2)
1169      end)
1170
1171      eq(forever_child:status(), 'awaiting')
1172      main:close()
1173      check_task_err(main, 'closed')
1174      check_task_err(forever_child, 'closed')
1175    end)
1176
1177    it_exec('child failure while parent is suspended closes siblings', function()
1178      local sibling --- @type vim.async.Task
1179      local continued = false
1180
1181      local parent = run(function()
1182        run(function()
1183          Async.sleep(1)
1184          error('CHILD_ERROR')
1185        end)
1186
1187        sibling = run(eternity)
1188        Async.sleep(100)
1189        continued = true
1190      end)
1191
1192      check_task_err(parent, 'child error: .*async_spec.lua:%d+: CHILD_ERROR')
1193      check_task_err(sibling, 'closed')
1194      eq(false, continued)
1195    end)
1196
1197    it_exec('should not close the parent task when child task is closed', function()
1198      run(function()
1199        run(eternity):close()
1200      end):wait()
1201    end)
1202  end)
1203
1204  describe('semaphore', function()
1205    it_exec('rejects invalid permit counts', function()
1206      for _, permits in ipairs({ 0, -1, 1.5, math.huge }) do
1207        local ok, err = pcall(Async.semaphore, permits)
1208        eq(false, ok)
1209        --- @cast err string
1210        assert(
1211          err:match('permits: expected positive integer'),
1212          'Unexpected error: ' .. tostring(err)
1213        )
1214      end
1215    end)
1216
1217    it_exec('runs', function()
1218      local ret = {}
1219      run(function()
1220        local semaphore = Async.semaphore(3)
1221        local tasks = {} --- @type vim.async.Task<nil>[]
1222        for i = 1, 5 do
1223          tasks[#tasks + 1] = run(function()
1224            semaphore:with(function()
1225              ret[#ret + 1] = 'start' .. i
1226              await(vim.schedule)
1227              ret[#ret + 1] = 'end' .. i
1228            end)
1229          end)
1230        end
1231        local next_task = Async.iter(tasks)
1232        while true do
1233          local task = next_task()
1234          if not task then
1235            break
1236          end
1237          await(task)
1238        end
1239      end):wait()
1240
1241      eq({
1242        'start1',
1243        'start2',
1244        'start3',
1245        'end1',
1246        'end2',
1247        'end3',
1248        'start4',
1249        'start5',
1250        'end4',
1251        'end5',
1252      }, ret)
1253    end)
1254
1255    it_exec('ping pong', function()
1256      local msgs = {}
1257      local ball = { hits = 0 }
1258      local max_hits = 10
1259
1260      --- @async
1261      --- @param name string
1262      --- @param sem vim.async.Semaphore
1263      local function player(name, sem)
1264        while ball.hits < max_hits do
1265          local ok, err = pcall(sem.acquire, sem)
1266          if not ok or ball.hits >= max_hits then
1267            if not ok and not tostring(err):match('closed') then
1268              error(err)
1269            end
1270            break
1271          end
1272
1273          ball.hits = ball.hits + 1
1274          msgs[#msgs + 1] = name
1275          Async.sleep(2)
1276          sem:release()
1277        end
1278      end
1279
1280      run(function()
1281        local sem = Async.semaphore(1)
1282        local p1 = run(player, 'ping', sem)
1283        local p2 = run(player, 'pong', sem)
1284        local next_task = Async.iter({ p1, p2 })
1285        while true do
1286          local task = next_task()
1287          if not task then
1288            break
1289          end
1290          await(task)
1291        end
1292      end):wait()
1293
1294      eq({ 'ping', 'pong', 'ping', 'pong', 'ping', 'pong', 'ping', 'pong', 'ping', 'pong' }, msgs)
1295    end)
1296
1297    it_exec('does not lose a semaphore wake after closing a waiter', function()
1298      local sem = Async.semaphore(1)
1299      local second_acquired = false
1300
1301      run(function()
1302        sem:acquire()
1303
1304        local first = run(function()
1305          sem:acquire()
1306        end)
1307
1308        local second = run(function()
1309          sem:acquire()
1310          second_acquired = true
1311        end)
1312
1313        Async.checkpoint()
1314        first:close()
1315        Async.pawait(first)
1316
1317        sem:release()
1318        await(second)
1319      end):wait(100)
1320
1321      eq(true, second_acquired)
1322    end)
1323
1324    it_exec('releases semaphore permits when with errors', function()
1325      run(function()
1326        local sem = Async.semaphore(1)
1327
1328        local ok, err = pcall(function()
1329          sem:with(function()
1330            error('WITH_ERROR')
1331          end)
1332        end)
1333
1334        eq(false, ok)
1335        --- @cast err string
1336        assert(err:match('WITH_ERROR'), 'Expected WITH_ERROR, got: ' .. tostring(err))
1337
1338        sem:acquire()
1339        sem:release()
1340      end):wait(100)
1341    end)
1342
1343    it_exec('releases semaphore permits when with is cancelled', function()
1344      local release --- @type fun()?
1345      local sem = Async.semaphore(1)
1346
1347      local task = run(function()
1348        sem:with(function()
1349          await(function(callback)
1350            release = callback
1351          end)
1352        end)
1353      end)
1354
1355      run(function()
1356        Async.checkpoint()
1357        assert(release, 'semaphore body did not start')
1358
1359        task:close()
1360        Async.pawait(task)
1361
1362        sem:acquire()
1363        sem:release()
1364      end):wait(100)
1365
1366      check_task_err(task, 'closed')
1367    end)
1368
1369    it_exec('does not resume semaphore waiters inline on release', function()
1370      local results = {}
1371
1372      run(function()
1373        local sem = Async.semaphore(1)
1374        sem:acquire()
1375
1376        run(function()
1377          sem:acquire()
1378          results[#results + 1] = 'waiter_acquired'
1379        end)
1380
1381        Async.checkpoint()
1382        results[#results + 1] = 'before_release'
1383        sem:release()
1384        results[#results + 1] = 'after_release'
1385
1386        eq({ 'before_release', 'after_release' }, results)
1387        await(vim.schedule)
1388        eq({ 'before_release', 'after_release', 'waiter_acquired' }, results)
1389      end):wait(100)
1390    end)
1391  end)
1392
1393  describe('queue', function()
1394    it_exec('does not resume get waiters inline on put_nowait', function()
1395      local new_queue = require('vim.async._queue')
1396      local results = {}
1397
1398      run(function()
1399        local queue = new_queue()
1400
1401        run(function()
1402          local item = queue:get()
1403          results[#results + 1] = 'got_' .. item
1404        end)
1405
1406        Async.checkpoint()
1407        results[#results + 1] = 'before_put'
1408        queue:put_nowait('item')
1409        results[#results + 1] = 'after_put'
1410
1411        eq({ 'before_put', 'after_put' }, results)
1412        await(vim.schedule)
1413        eq({ 'before_put', 'after_put', 'got_item' }, results)
1414      end):wait(100)
1415    end)
1416
1417    it_exec('get waiters retry if a deferred item is consumed first', function()
1418      local new_queue = require('vim.async._queue')
1419      local results = {}
1420
1421      run(function()
1422        local queue = new_queue()
1423
1424        run(function()
1425          results[#results + 1] = queue:get()
1426        end)
1427
1428        Async.checkpoint()
1429        queue:put_nowait('first')
1430        eq('first', queue:get_nowait())
1431
1432        await(vim.schedule)
1433        eq({}, results)
1434
1435        queue:put_nowait('second')
1436        await(vim.schedule)
1437        eq({ 'second' }, results)
1438      end):wait(100)
1439    end)
1440
1441    it_exec('does not resume put waiters inline on get_nowait', function()
1442      local new_queue = require('vim.async._queue')
1443      local results = {}
1444
1445      run(function()
1446        local queue = new_queue(1)
1447        queue:put_nowait('first')
1448
1449        run(function()
1450          queue:put('second')
1451          results[#results + 1] = 'put_second'
1452        end)
1453
1454        Async.checkpoint()
1455        results[#results + 1] = 'before_get'
1456        eq('first', queue:get_nowait())
1457        results[#results + 1] = 'after_get'
1458
1459        eq({ 'before_get', 'after_get' }, results)
1460        await(vim.schedule)
1461        eq({ 'before_get', 'after_get', 'put_second' }, results)
1462      end):wait(100)
1463    end)
1464
1465    it_exec('put waiters retry if a deferred slot is filled first', function()
1466      local new_queue = require('vim.async._queue')
1467      local results = {}
1468
1469      run(function()
1470        local queue = new_queue(1)
1471        queue:put_nowait('first')
1472
1473        run(function()
1474          queue:put('second')
1475          results[#results + 1] = 'put_second'
1476        end)
1477
1478        Async.checkpoint()
1479        eq('first', queue:get_nowait())
1480        queue:put_nowait('interloper')
1481
1482        await(vim.schedule)
1483        eq({}, results)
1484
1485        eq('interloper', queue:get_nowait())
1486        await(vim.schedule)
1487        eq({ 'put_second' }, results)
1488        eq('second', queue:get_nowait())
1489      end):wait(100)
1490    end)
1491  end)
1492
1493  describe('coroutine safety', function()
1494    it_exec('does not allow coroutine.yield', function()
1495      local task = run(function()
1496        coroutine.yield('This will cause an error.')
1497      end)
1498      check_task_err(task, 'Unexpected coroutine.yield().*')
1499    end)
1500
1501    it_exec('does not allow coroutine.resume', function()
1502      local co --- @type thread
1503      local task = run(function()
1504        co = coroutine.running()
1505        eternity()
1506      end)
1507
1508      local status, err = coroutine.resume(co)
1509      assert(not status, 'Expected coroutine.resume to fail')
1510      eq(err, 'Unexpected coroutine.resume()')
1511      check_task_err(task, 'Unexpected coroutine.resume%(%)')
1512    end)
1513
1514    it_exec('does not allow coroutine.resume when awaiting detached task', function()
1515      local t = run(eternity)
1516      local co --- @type thread
1517      local task = run(function()
1518        co = coroutine.running()
1519        await(t)
1520      end)
1521
1522      local status, err = coroutine.resume(co)
1523      assert(not status, 'Expected coroutine.resume to fail')
1524      eq(err, 'Unexpected coroutine.resume()')
1525      check_task_err(task, 'Unexpected coroutine.resume%(%)')
1526      t:close()
1527    end)
1528
1529    it_exec('preserves child errors after invalid coroutine.resume', function()
1530      local blocker = run(eternity)
1531      local co --- @type thread
1532      local parent = run(function()
1533        co = coroutine.running()
1534        run(function()
1535          await(vim.schedule)
1536          error('CHILD ERROR')
1537        end)
1538        await(blocker)
1539      end)
1540
1541      local status, err = coroutine.resume(co)
1542      assert(not status, 'Expected coroutine.resume to fail')
1543      eq(err, 'Unexpected coroutine.resume()')
1544      local check_ok, check_err =
1545        pcall(check_task_err, parent, 'child error: .*async_spec.lua:%d+: CHILD ERROR')
1546
1547      blocker:close()
1548      check_task_err(blocker, 'closed')
1549
1550      if not check_ok then
1551        error(check_err, 0)
1552      end
1553    end)
1554  end)
1555
1556  describe('inspect_tree', function()
1557    local outside_tree = t.dedent([=[
1558      parent %[awaiting%]
1559      ├─ child1 %[awaiting%]
1560      ├─ child2 %[awaiting%]
1561      └─ child3 %[awaiting%]
1562         ├─ sub_child1 %[awaiting%]
1563         ├─ sub_child2 %[awaiting%]
1564         └─ %[awaiting%]]=])
1565    local inside_tree = t.dedent([=[
1566      parent %[awaiting%]
1567      ├─ child1 %[awaiting%]
1568      ├─ child2 %[awaiting%]
1569      └─ child3 %[running%]
1570         ├─ sub_child1 %[awaiting%]
1571         ├─ sub_child2 %[awaiting%]
1572         └─ %[awaiting%]]=])
1573    local jit_tree = t.dedent([=[
1574      parent@.*async_spec.lua:%d+ %[awaiting%]
1575      └─ child@.*async_spec.lua:%d+ %[awaiting%]]=])
1576    local puc_tree = t.dedent([=[
1577      parent=.* %[awaiting%]
1578      └─ child=.* %[awaiting%]]=])
1579
1580    it_exec('outside of tasks', function(expected)
1581      local parent = run('parent', function()
1582        run('child1', eternity)
1583        run('child2', eternity)
1584        run('child3', function(...)
1585          run('sub_child1', eternity)
1586          run('sub_child2', eternity)
1587          run(eternity)
1588        end)
1589      end)
1590
1591      eq(p(expected), Async._inspect_tree())
1592
1593      parent:close()
1594      check_task_err(parent, 'closed')
1595    end, outside_tree)
1596
1597    it_exec('inside a task', function(expected)
1598      local inspect
1599      local parent = run('parent', function()
1600        run('child1', eternity)
1601        run('child2', eternity)
1602        run('child3', function(...)
1603          run('sub_child1', eternity)
1604          run('sub_child2', eternity)
1605          run(eternity)
1606          inspect = Async._inspect_tree()
1607        end)
1608      end)
1609
1610      eq(p(expected), inspect)
1611
1612      parent:close()
1613      check_task_err(parent, 'closed')
1614    end, inside_tree)
1615
1616    it_exec('can show task creation locations in debug mode', function(jit_expected, puc_expected)
1617      AsyncRuntime.config({ debug = true })
1618      local parent
1619      local ok, err = pcall(function()
1620        parent = run('parent', function()
1621          run('child', eternity)
1622        end)
1623
1624        local expected = is_jit() and jit_expected or puc_expected
1625
1626        eq(p(expected), Async._inspect_tree())
1627      end)
1628      if parent then
1629        parent:close()
1630      end
1631      AsyncRuntime.config({ debug = false })
1632      if parent then
1633        check_task_err(parent, 'closed')
1634      end
1635      if not ok then
1636        error(err, 0)
1637      end
1638    end, jit_tree, puc_tree)
1639  end)
1640
1641  describe('pcall and task-control errors', function()
1642    it_exec('child errors remain terminal after pcall catches delivery', function()
1643      local results = {}
1644      local parent = run(function()
1645        local _child = run(function()
1646          Async.sleep(5)
1647          error('CHILD ERROR')
1648        end)
1649
1650        local ok1, err1 = pcall(function()
1651          Async.sleep(100)
1652        end)
1653
1654        if not ok1 then
1655          results[#results + 1] = 'caught_first'
1656          results[#results + 1] = err1:match('CHILD ERROR') and 'has_error' or 'no_error'
1657        end
1658
1659        local ok2, err2 = pcall(function()
1660          Async.sleep(1)
1661        end)
1662
1663        if not ok2 then
1664          results[#results + 1] = 'caught_second'
1665          results[#results + 1] = err2:match('CHILD ERROR') and 'has_error' or 'no_error'
1666        else
1667          results[#results + 1] = 'no_second_error'
1668        end
1669
1670        results[#results + 1] = 'returned'
1671      end)
1672
1673      local ok, err = parent:pwait(200)
1674      eq(false, ok)
1675      --- @cast err string
1676      assert(err:match('child error:.*CHILD ERROR'), 'Expected child error, got: ' .. tostring(err))
1677
1678      eq({
1679        'caught_first',
1680        'has_error',
1681        'caught_second',
1682        'has_error',
1683        'returned',
1684      }, results)
1685    end)
1686
1687    it_exec('awaited child errors remain terminal without child wrapper', function()
1688      local results = {}
1689      local parent = run(function()
1690        local child = run(function()
1691          error('AWAITED CHILD ERROR')
1692        end)
1693
1694        local ok1, err1 = pcall(function()
1695          await(child)
1696        end)
1697
1698        if not ok1 then
1699          results[#results + 1] = err1:match('AWAITED CHILD ERROR') and 'caught_child' or 'other'
1700          results[#results + 1] = err1:match('child error:') and 'wrapped' or 'unwrapped'
1701        end
1702
1703        local ok2, err2 = pcall(function()
1704          Async.sleep(1)
1705        end)
1706
1707        if not ok2 then
1708          results[#results + 1] = err2:match('AWAITED CHILD ERROR') and 'caught_again' or 'other'
1709          results[#results + 1] = err2:match('child error:') and 'wrapped' or 'unwrapped'
1710        end
1711
1712        results[#results + 1] = 'returned'
1713      end)
1714
1715      local ok, err = parent:pwait(200)
1716      eq(false, ok)
1717      --- @cast err string
1718      assert(
1719        err:match('.*async_spec.lua:%d+: AWAITED CHILD ERROR'),
1720        'Expected awaited child error, got: ' .. tostring(err)
1721      )
1722      assert(not err:match('child error:'), 'Did not expect child wrapper, got: ' .. err)
1723
1724      eq({
1725        'caught_child',
1726        'unwrapped',
1727        'caught_again',
1728        'unwrapped',
1729        'returned',
1730      }, results)
1731    end)
1732
1733    it_exec('false awaited child errors remain terminal after pcall catches delivery', function()
1734      local parent = run(function()
1735        local child = run(function()
1736          error(false, 0)
1737        end)
1738
1739        local ok1, err1 = pcall(function()
1740          await(child)
1741        end)
1742
1743        eq(false, ok1)
1744        eq(false, err1)
1745
1746        local ok2, err2 = pcall(function()
1747          Async.sleep(1)
1748        end)
1749
1750        eq(false, ok2)
1751        eq(false, err2)
1752      end)
1753
1754      local ok, err = parent:pwait(200)
1755      eq(false, ok)
1756      eq(false, err)
1757    end)
1758
1759    it_exec('pawait returns successful task results', function()
1760      local parent = run(function()
1761        local ok, a, b, c = Async.pawait(run(function()
1762          Async.sleep(1)
1763          return 1, 'two', true
1764        end))
1765
1766        eq(true, ok)
1767        eq(1, a)
1768        eq('two', b)
1769        eq(true, c)
1770
1771        return 'parent ok'
1772      end)
1773
1774      eq('parent ok', parent:wait(100))
1775    end)
1776
1777    it_exec('pawait accepts await callback overloads', function()
1778      local parent = run(function()
1779        local ok1, value = Async.pawait(function(callback)
1780          vim.schedule(function()
1781            callback('scheduled')
1782          end)
1783        end)
1784
1785        local ok2, a, b = Async.pawait(2, function(prefix, callback)
1786          vim.schedule(function()
1787            callback(prefix, 'done')
1788          end)
1789        end, 'arg')
1790
1791        eq({ true, 'scheduled' }, { ok1, value })
1792        eq({ true, 'arg', 'done' }, { ok2, a, b })
1793
1794        return 'parent ok'
1795      end)
1796
1797      eq('parent ok', parent:wait(100))
1798    end)
1799
1800    it_exec('pawait returns awaitable setup errors as data', function()
1801      local parent = run(function()
1802        local ok, err = Async.pawait(function(_callback)
1803          error()
1804        end)
1805
1806        eq(false, ok)
1807        eq('error(nil)', err)
1808
1809        return 'parent ok'
1810      end)
1811
1812      eq('parent ok', parent:wait(100))
1813    end)
1814
1815    it_exec('pawait keeps synchronous results before a setup error', function()
1816      local parent = run(function()
1817        local function callback_then_error(callback)
1818          callback('result')
1819          error('LATE_SETUP_ERROR')
1820        end
1821
1822        local ok, result = Async.pawait(callback_then_error)
1823        eq({ true, 'result' }, { ok, result })
1824
1825        local raw_ok, err = pcall(await, callback_then_error)
1826        eq(false, raw_ok)
1827        assert(tostring(err):match('LATE_SETUP_ERROR'), tostring(err))
1828      end)
1829
1830      parent:wait(100)
1831    end)
1832
1833    it_exec('pawait ignores a late callback after setup fails', function()
1834      local child --- @type vim.async.Task
1835      local callback_ran = false
1836      local parent = run(function()
1837        child = run(function()
1838          Async.sleep(5)
1839          return 'child finished'
1840        end)
1841
1842        local ok, err = Async.pawait(function(callback)
1843          vim.schedule(function()
1844            callback_ran = true
1845            callback('late result')
1846          end)
1847          error('SETUP_ERROR')
1848        end)
1849
1850        eq(false, ok)
1851        assert(tostring(err):match('SETUP_ERROR'), tostring(err))
1852        return 'parent finished'
1853      end)
1854
1855      eq('parent finished', parent:wait(100))
1856      eq(true, callback_ran)
1857      eq('child finished', child:wait(100))
1858    end)
1859
1860    it_exec('pawait returns synchronous child errors as data', function()
1861      local results = {}
1862      local parent = run(function()
1863        local child = run(function()
1864          results[#results + 1] = 'child_started'
1865          error('SYNC CHILD ERROR')
1866        end)
1867
1868        results[#results + 1] = 'after_run'
1869        local ok, err = Async.pawait(child)
1870
1871        eq(false, ok)
1872        --- @cast err string
1873        results[#results + 1] = err:match('SYNC CHILD ERROR') and 'got_error' or 'other'
1874        results[#results + 1] = err:match('child error:') and 'wrapped' or 'unwrapped'
1875
1876        Async.sleep(1)
1877        results[#results + 1] = 'continued'
1878
1879        return 'parent ok'
1880      end)
1881
1882      eq('parent ok', parent:wait(100))
1883      eq({
1884        'after_run',
1885        'child_started',
1886        'got_error',
1887        'unwrapped',
1888        'continued',
1889      }, results)
1890    end)
1891
1892    it_exec('pawait returns asynchronous child errors as data', function()
1893      local results = {}
1894      local parent = run(function()
1895        local ok, err = Async.pawait(run(function()
1896          Async.sleep(1)
1897          error('ASYNC CHILD ERROR')
1898        end))
1899
1900        eq(false, ok)
1901        --- @cast err string
1902        results[#results + 1] = err:match('ASYNC CHILD ERROR') and 'got_error' or 'other'
1903        results[#results + 1] = err:match('child error:') and 'wrapped' or 'unwrapped'
1904
1905        Async.sleep(1)
1906        results[#results + 1] = 'continued'
1907
1908        return 'parent ok'
1909      end)
1910
1911      eq('parent ok', parent:wait(100))
1912      eq({
1913        'got_error',
1914        'unwrapped',
1915        'continued',
1916      }, results)
1917    end)
1918
1919    it_exec('pawait does not protect current task cancellation', function()
1920      local results = {}
1921      local parent = run(function()
1922        local ok, err = pcall(function()
1923          Async.pawait(function(_callback)
1924            return add_handle('pawait_current_cancellation_timer', vim.uv.new_timer())
1925          end)
1926        end)
1927
1928        eq(false, ok)
1929        results[#results + 1] = is_closed_error(err) and 'caught_closed' or 'other_error'
1930        results[#results + 1] = Async.is_closing() and 'is_closing' or 'not_closing'
1931        results[#results + 1] = 'cleanup'
1932      end)
1933
1934      parent:close()
1935
1936      check_task_err(parent, 'closed')
1937      eq({
1938        'caught_closed',
1939        'is_closing',
1940        'cleanup',
1941      }, results)
1942    end)
1943
1944    it_exec('pawait does not protect unrelated current task errors', function()
1945      local results = {}
1946      local parent = run(function()
1947        local _child = run(function()
1948          Async.sleep(5)
1949          error('CHILD ERROR')
1950        end)
1951
1952        local ok, err = pcall(function()
1953          Async.pawait(function(callback)
1954            local timer = add_handle('pending_child_error_timer', vim.uv.new_timer())
1955            timer:start(100, 0, function()
1956              timer:close()
1957              callback('done')
1958            end)
1959            return timer
1960          end)
1961        end)
1962
1963        eq(false, ok)
1964        --- @cast err string
1965        results[#results + 1] = err:match('child error:.*CHILD ERROR') and 'child_error'
1966          or 'other_error'
1967        results[#results + 1] = Async.is_closing() and 'is_closing' or 'not_closing'
1968        results[#results + 1] = 'cleanup'
1969      end)
1970
1971      local ok, err = parent:pwait(200)
1972      eq(false, ok)
1973      --- @cast err string
1974      assert(err:match('child error:.*CHILD ERROR'), 'Expected child error, got: ' .. tostring(err))
1975
1976      eq({
1977        'child_error',
1978        'not_closing',
1979        'cleanup',
1980      }, results)
1981    end)
1982
1983    it_exec('cancellations are level-triggered (persist across catches)', function()
1984      local results = {}
1985      local task = run(function()
1986        local ok1, err1 = pcall(function()
1987          Async.sleep(100)
1988        end)
1989
1990        if not ok1 then
1991          results[#results + 1] = 'caught_first'
1992          results[#results + 1] = is_closed_error(err1) and 'is_closed' or 'other_error'
1993        end
1994
1995        local ok2, err2 = pcall(function()
1996          Async.sleep(1)
1997        end)
1998
1999        if not ok2 then
2000          results[#results + 1] = 'caught_second'
2001          results[#results + 1] = is_closed_error(err2) and 'is_closed' or 'other_error'
2002        end
2003
2004        results[#results + 1] = 'should_not_reach'
2005      end)
2006
2007      task:close()
2008
2009      check_task_err(task, 'closed')
2010
2011      eq({
2012        'caught_first',
2013        'is_closed',
2014        'caught_second',
2015        'is_closed',
2016        'should_not_reach',
2017      }, results)
2018    end)
2019
2020    it_exec('checkpoint rethrows current task cancellation after cleanup', function()
2021      local results = {}
2022      local task = run(function()
2023        local ok, err = pcall(function()
2024          Async.sleep(100)
2025        end)
2026
2027        eq(false, ok)
2028        results[#results + 1] = is_closed_error(err) and 'caught_closed' or 'other_error'
2029        results[#results + 1] = 'cleanup'
2030
2031        Async.checkpoint()
2032        results[#results + 1] = 'after_checkpoint'
2033      end)
2034
2035      task:close()
2036
2037      check_task_err(task, 'closed')
2038
2039      eq({
2040        'caught_closed',
2041        'cleanup',
2042      }, results)
2043    end)
2044
2045    it_exec('checkpoint rethrows current task failure after cleanup', function()
2046      local results = {}
2047      local parent = run(function()
2048        local _child = run(function()
2049          Async.sleep(5)
2050          error('CHILD ERROR')
2051        end)
2052
2053        local ok, err = pcall(function()
2054          Async.sleep(100)
2055        end)
2056
2057        eq(false, ok)
2058        --- @cast err string
2059        results[#results + 1] = err:match('CHILD ERROR') and 'caught_child_error' or 'other_error'
2060        results[#results + 1] = 'cleanup'
2061
2062        Async.checkpoint()
2063        results[#results + 1] = 'after_checkpoint'
2064      end)
2065
2066      check_task_err(parent, 'child error:.*CHILD ERROR')
2067
2068      eq({
2069        'caught_child_error',
2070        'cleanup',
2071      }, results)
2072    end)
2073
2074    it_exec('can recover synchronous errors inside async tasks', function()
2075      local results = {}
2076      run(function()
2077        local ok = pcall(function()
2078          error('BAD CONFIG')
2079        end)
2080
2081        if not ok then
2082          results[#results + 1] = 'error_caught'
2083        end
2084
2085        Async.sleep(1)
2086        results[#results + 1] = 'finished'
2087      end):wait(200)
2088
2089      eq({
2090        'error_caught',
2091        'finished',
2092      }, results)
2093    end)
2094
2095    it_exec('cancellation persists even after pcall catches it', function()
2096      local results = {}
2097      local task = run(function()
2098        for i = 1, 5 do
2099          local ok, err = pcall(function()
2100            Async.sleep(10)
2101          end)
2102
2103          if not ok then
2104            if is_closed_error(err) then
2105              results[#results + 1] = ('closed_iteration_%d'):format(i)
2106            else
2107              results[#results + 1] = ('error_iteration_%d'):format(i)
2108            end
2109          else
2110            results[#results + 1] = ('success_iteration_%d'):format(i)
2111          end
2112        end
2113      end)
2114
2115      task:close()
2116
2117      check_task_err(task, 'closed')
2118
2119      eq({
2120        'closed_iteration_1',
2121        'closed_iteration_2',
2122        'closed_iteration_3',
2123        'closed_iteration_4',
2124        'closed_iteration_5',
2125      }, results)
2126    end)
2127
2128    it_exec('is_closing() reflects level-triggered cancellation state', function()
2129      local results = {}
2130      local task = run(function()
2131        for _ = 1, 3 do
2132          results[#results + 1] = ('is_closing_%d'):format(Async.is_closing() and 1 or 0)
2133
2134          local ok = pcall(function()
2135            Async.sleep(10)
2136          end)
2137
2138          if not ok then
2139            results[#results + 1] = ('after_catch_is_closing_%d'):format(
2140              Async.is_closing() and 1 or 0
2141            )
2142          end
2143        end
2144      end)
2145
2146      task:close()
2147
2148      check_task_err(task, 'closed')
2149
2150      eq({
2151        'is_closing_0',
2152        'after_catch_is_closing_1',
2153        'is_closing_1',
2154        'after_catch_is_closing_1',
2155        'is_closing_1',
2156        'after_catch_is_closing_1',
2157      }, results)
2158    end)
2159
2160    it_exec('first child error remains pending across subsequent awaits', function()
2161      local results = {}
2162      local release_first --- @type fun()?
2163
2164      -- Child failure, rather than this awaitable, resumes the parent.
2165      local function wait_for_child_error()
2166        await(function() end)
2167      end
2168
2169      local parent = run(function()
2170        local _child1 = run(function()
2171          await(function(callback)
2172            release_first = callback
2173          end)
2174          error('ERROR_1')
2175        end)
2176
2177        local release_second --- @type fun()?
2178        local _child2 = run(function()
2179          await(function(callback)
2180            release_second = callback
2181          end)
2182          error('ERROR_2')
2183        end)
2184
2185        local ok1, err1 = pcall(wait_for_child_error)
2186
2187        if not ok1 then
2188          results[#results + 1] = err1:match('ERROR_1') and 'got_error_1' or 'other'
2189        end
2190
2191        assert(release_second)
2192        release_second()
2193
2194        local ok2, err2 = pcall(wait_for_child_error)
2195
2196        if not ok2 then
2197          results[#results + 1] = err2:match('ERROR_1') and 'got_error_1_again' or 'other'
2198        end
2199
2200        results[#results + 1] = 'returned'
2201      end)
2202
2203      assert(release_first)
2204      release_first()
2205
2206      local ok, err = parent:pwait(200)
2207      eq(false, ok)
2208      --- @cast err string
2209      assert(
2210        err:match('child error:.*ERROR_1'),
2211        'Expected first child error, got: ' .. tostring(err)
2212      )
2213
2214      eq({
2215        'got_error_1',
2216        'got_error_1_again',
2217        'returned',
2218      }, results)
2219    end)
2220
2221    it_exec('task error takes precedence over cancellation when both occur', function()
2222      local task = run(function()
2223        pcall(function()
2224          Async.sleep(10)
2225        end)
2226
2227        error('TASK_ERROR')
2228      end)
2229
2230      task:close()
2231
2232      local ok, err = task:pwait(100)
2233      assert(not ok, 'Expected task to error')
2234      eq(true, err:match('TASK_ERROR') ~= nil, 'Expected TASK_ERROR, got: ' .. tostring(err))
2235    end)
2236
2237    it_exec(
2238      'cancellation takes precedence when task completes successfully while closing',
2239      function()
2240        local results = {}
2241        local task = run(function()
2242          local ok, err = pcall(function()
2243            await(function(_callback)
2244              return {
2245                close = function(_, callback)
2246                  results[#results + 1] = 'close_called'
2247                  callback()
2248                end,
2249              }
2250            end)
2251          end)
2252
2253          eq(false, ok)
2254          eq(true, is_closed_error(err), 'Expected closed error, got: ' .. tostring(err))
2255          results[#results + 1] = 'caught_close'
2256          results[#results + 1] = 'completed'
2257          return 'SUCCESS'
2258        end)
2259
2260        eq('awaiting', task:status())
2261        task:close()
2262        check_task_err(task, 'closed')
2263
2264        eq({
2265          'close_called',
2266          'caught_close',
2267          'completed',
2268        }, results)
2269      end
2270    )
2271  end)
2272
2273  describe('edge case tests', function()
2274    it_exec('handles awaiting closable that is already closing', function()
2275      -- Test for potential issue where is_closing() returns true
2276      local close_count = 0
2277      local callback_called = false
2278
2279      local closable = {
2280        _closing = false,
2281        is_closing = function(self)
2282          return self._closing
2283        end,
2284        close = function(self, cb)
2285          close_count = close_count + 1
2286          self._closing = true
2287          if cb then
2288            vim.schedule(cb)
2289          end
2290        end,
2291      }
2292
2293      local task = run(function()
2294        -- Start closing the closable
2295        closable:close()
2296
2297        -- Now try to await something that returns this already-closing closable
2298        local result = await(function(callback)
2299          vim.schedule(function()
2300            callback('RESULT')
2301          end)
2302          return closable
2303        end)
2304
2305        callback_called = true
2306        return result
2307      end)
2308
2309      local result = task:wait(100)
2310      eq('RESULT', result)
2311      eq(true, callback_called)
2312      -- The closable should only be closed once (by the explicit close call)
2313      -- handle_close_awaiting should detect is_closing and not call close again
2314      eq(1, close_count)
2315    end)
2316
2317    it_exec('child error during parent finalization is handled', function()
2318      local parent = run(function()
2319        local _child = run(function()
2320          Async.sleep(5)
2321          error('CHILD_ERROR')
2322        end)
2323
2324        -- Returning starts finalization, which waits for attached child work.
2325      end)
2326
2327      local ok, err = parent:pwait(100)
2328
2329      eq(false, ok)
2330      --- @cast err string
2331      assert(err:match('child error:.*CHILD_ERROR'), 'Expected child error, got: ' .. tostring(err))
2332    end)
2333
2334    it_exec('child error formatting cannot interrupt parent finalization', function()
2335      local bad_error = setmetatable({}, {
2336        __tostring = function()
2337          error('TOSTRING_ERROR')
2338        end,
2339      })
2340
2341      local parent = run(function()
2342        local _child = run(function()
2343          Async.sleep(1)
2344          error(bad_error, 0)
2345        end)
2346      end)
2347
2348      check_task_err(parent, 'child error: <unprintable error>')
2349    end)
2350
2351    it_exec('child error during parent finalization completes once and closes siblings', function()
2352      local completions = 0
2353      local sibling --- @type vim.async.Task
2354
2355      local parent = run(function()
2356        local _child = run(function()
2357          Async.sleep(1)
2358          error('CHILD_ERROR')
2359        end)
2360
2361        sibling = run(eternity)
2362      end)
2363
2364      parent:on_complete(function()
2365        completions = completions + 1
2366      end)
2367
2368      local ok, err = parent:pwait(100)
2369
2370      eq(false, ok)
2371      --- @cast err string
2372      assert(err:match('child error:.*CHILD_ERROR'), 'Expected child error, got: ' .. tostring(err))
2373      eq(1, completions)
2374      check_task_err(sibling, 'closed')
2375    end)
2376
2377    it_exec('later child error during parent finalization closes earlier siblings', function()
2378      local completions = 0
2379      local sibling --- @type vim.async.Task
2380
2381      local parent = run(function()
2382        sibling = run(eternity)
2383
2384        local _child = run(function()
2385          Async.sleep(1)
2386          error('CHILD_ERROR')
2387        end)
2388      end)
2389
2390      parent:on_complete(function()
2391        completions = completions + 1
2392      end)
2393
2394      local ok, err = parent:pwait(100)
2395
2396      eq(false, ok)
2397      --- @cast err string
2398      assert(err:match('child error:.*CHILD_ERROR'), 'Expected child error, got: ' .. tostring(err))
2399      eq(1, completions)
2400      check_task_err(sibling, 'closed')
2401    end)
2402
2403    it_exec('child error during parent finalization waits for sibling cleanup', function()
2404      local cleanup_done = false
2405      local sibling --- @type vim.async.Task
2406
2407      local parent = run(function()
2408        sibling = run(function()
2409          await(function()
2410            return {
2411              close = function(_, callback)
2412                vim.schedule(function()
2413                  cleanup_done = true
2414                  callback()
2415                end)
2416              end,
2417            }
2418          end)
2419        end)
2420
2421        local _child = run(function()
2422          Async.sleep(1)
2423          error('CHILD_ERROR')
2424        end)
2425      end)
2426
2427      local ok, err = parent:pwait(100)
2428
2429      eq(false, ok)
2430      --- @cast err string
2431      assert(err:match('child error:.*CHILD_ERROR'), 'Expected child error, got: ' .. tostring(err))
2432      eq(true, cleanup_done)
2433      check_task_err(sibling, 'closed')
2434    end)
2435
2436    it_exec('parent failure waits for every child cleanup', function()
2437      local first_cleanup_done = false
2438      local second_cleanup_done = false
2439
2440      local parent = run(function()
2441        run(function()
2442          await(function()
2443            return {
2444              close = function(_, callback)
2445                first_cleanup_done = true
2446                callback()
2447              end,
2448            }
2449          end)
2450        end)
2451
2452        run(function()
2453          await(function()
2454            return {
2455              close = function(_, callback)
2456                vim.schedule(function()
2457                  second_cleanup_done = true
2458                  callback()
2459                end)
2460              end,
2461            }
2462          end)
2463        end)
2464
2465        Async.checkpoint()
2466        error('PARENT_ERROR')
2467      end)
2468
2469      local ok, err = parent:pwait(100)
2470
2471      eq(false, ok)
2472      --- @cast err string
2473      assert(err:match('PARENT_ERROR'), 'Expected parent error, got: ' .. tostring(err))
2474      eq(true, first_cleanup_done)
2475      eq(true, second_cleanup_done)
2476    end)
2477
2478    it_exec('does not resume a closing task before awaitable cleanup', function()
2479      local operation_callback --- @type fun(...: any)
2480      local body_ran = false
2481      local cleanup_done = false
2482      local closable = { closing = false }
2483
2484      function closable:is_closing()
2485        return self.closing
2486      end
2487
2488      function closable:close(callback)
2489        self.closing = true
2490        operation_callback('RESULT')
2491        vim.schedule(function()
2492          cleanup_done = true
2493          callback()
2494        end)
2495      end
2496
2497      local task = run(function()
2498        Async.pawait(function(callback)
2499          operation_callback = callback
2500          return closable
2501        end)
2502        body_ran = true
2503      end)
2504
2505      task:close()
2506      check_task_err(task, 'closed')
2507
2508      eq(false, body_ran)
2509      eq(true, cleanup_done)
2510    end)
2511
2512    it_exec('future complete is one-shot', function()
2513      local future = require('vim.async._future')()
2514      future:complete(nil, 'first')
2515
2516      local ok, err = pcall(function()
2517        future:complete(nil, 'second')
2518      end)
2519
2520      eq(false, ok)
2521      --- @cast err string
2522      assert(err:match('Future is already completed'), 'Unexpected error: ' .. tostring(err))
2523
2524      local stat, result = future:result()
2525      eq(true, stat)
2526      eq('first', result)
2527    end)
2528
2529    it_exec('future false error still completes', function()
2530      local future = require('vim.async._future')()
2531      future:complete(false)
2532
2533      eq(true, future:completed())
2534
2535      local stat, err = future:result()
2536      eq(false, stat)
2537      eq(false, err)
2538    end)
2539
2540    it_exec('normalizes nil task errors', function()
2541      check_task_err(
2542        run(function()
2543          error()
2544        end),
2545        'error%(nil%)'
2546      )
2547    end)
2548
2549    it_exec('normalizes nil awaitable setup errors', function()
2550      local task = run(function()
2551        await(function()
2552          error()
2553        end)
2554      end)
2555
2556      check_task_err(task, 'error%(nil%)')
2557    end)
2558
2559    it_exec('normalizes nil close errors', function()
2560      local task = run(function()
2561        await(function()
2562          return {
2563            close = function()
2564              error()
2565            end,
2566          }
2567        end)
2568      end)
2569
2570      task:close()
2571      check_task_err(task, 'error%(nil%)')
2572    end)
2573
2574    it_exec('normalizes nil future callback errors', function()
2575      local future = require('vim.async._future')()
2576      future:on_complete(function()
2577        error()
2578      end)
2579
2580      local ok, err = pcall(function()
2581        future:complete(nil, 'value')
2582      end)
2583
2584      eq(false, ok)
2585      --- @cast err string
2586      assert(err:match('error%(nil%)'), 'Unexpected error: ' .. tostring(err))
2587    end)
2588
2589    it_exec('continues future callbacks after an unprintable error', function()
2590      local future = require('vim.async._future')()
2591      local observed = false
2592      local unprintable = setmetatable({}, {
2593        __tostring = function()
2594          error('TOSTRING_ERROR')
2595        end,
2596      })
2597
2598      future:on_complete(function()
2599        error(unprintable)
2600      end)
2601      future:on_complete(function()
2602        observed = true
2603      end)
2604
2605      local ok, err = pcall(function()
2606        future:complete(nil, 'value')
2607      end)
2608
2609      eq(false, ok)
2610      eq(true, observed)
2611      assert(tostring(err):match('<unprintable error>'), 'Unexpected error: ' .. tostring(err))
2612    end)
2613
2614    it_exec('callback called multiple times is handled gracefully', function()
2615      -- Test that calling callback multiple times doesn't break things
2616      local call_count = 0
2617      local results = {}
2618
2619      local task = run(function()
2620        local result = await(function(callback)
2621          call_count = call_count + 1
2622          callback('FIRST_CALL')
2623
2624          -- Try calling again (should be ignored)
2625          vim.schedule(function()
2626            call_count = call_count + 1
2627            callback('SECOND_CALL')
2628          end)
2629        end)
2630
2631        table.insert(results, result)
2632        return result
2633      end)
2634
2635      local final_result = task:wait(100)
2636
2637      -- Should only get the first callback result
2638      eq('FIRST_CALL', final_result)
2639      eq(1, #results)
2640      eq('FIRST_CALL', results[1])
2641
2642      -- Wait a bit for the second callback to potentially fire
2643      run(function()
2644        Async.sleep(20)
2645      end):wait()
2646
2647      -- Both callbacks should have been called
2648      eq(2, call_count)
2649
2650      -- But only the first one should have been processed
2651      eq(1, #results)
2652    end)
2653
2654    it_exec('closable cleanup happens even if close() errors', function()
2655      -- Test that if a closable's close() method errors, we handle it gracefully
2656      local close_called = false
2657
2658      local task = run(function()
2659        local result = await(function(callback)
2660          local closable = {
2661            close = function()
2662              close_called = true
2663              error('CLOSE_ERROR')
2664            end,
2665          }
2666
2667          vim.schedule(function()
2668            callback('RESULT')
2669          end)
2670
2671          return closable
2672        end)
2673
2674        return result
2675      end)
2676
2677      task:close() -- This should trigger closing the closable
2678
2679      -- The task should complete with the close error
2680      local ok, err = task:pwait(100)
2681
2682      eq(true, close_called, 'close() should have been called')
2683      assert(not ok, 'Task should have errored')
2684      assert(err:match('CLOSE_ERROR'), 'Expected CLOSE_ERROR, got: ' .. tostring(err))
2685    end)
2686  end)
2687end)