(use-modules (knots) (fibers) (knots parallelism))

;; Deep call chain within the innermost fiber.  Each function calls the next
;; via `begin', placing the call in non-tail position so Guile's TCO does not
;; collapse the frames; all four frames survive and appear in the backtrace.
(define (deeply-nested x)
  (error "deeply nested error" x))  ; LAST BACKTRACE ENTRY HERE

(define (three-deep x)
  (fibers-map deeply-nested (list x)))

(define (two-deep x)
  (fibers-map three-deep (list x)))

(define (one-deep x)
  (fibers-map two-deep (list x)))

;; process-batch runs inside one fiber and dispatches the deep call chain into
;; a nested fiber via a second fibers-map, creating two fiber boundaries.
(define (process-batch items)
  (begin
    (fibers-map one-deep (list items))
    'unreachable))

(define (run-work)
  (begin
    (fibers-map process-batch '(1))
    'unreachable))

(define result
  (run-fibers
   (lambda ()
     ;; FIRST BACKTRACE ENTRY: (with-exception-handler
     (with-exception-handler
         (lambda (e)
           (print-backtrace-and-exception/knots e)
           (primitive-exit 1))
       run-work))
   #:hz 0 #:parallelism 1))

