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