@@ -34,24 +34,177 @@ traversal treat leaves differently, for performance.
3434
3535## Traversal orders and resource use
3636
37- Each form comes in five traversal orders: DFS, BFS, BFS Rev, wide DFS and wide
38- DFS Rev. Wide DFS goes depth first along a path, like DFS, but it emits all the
39- children of a node before it descends into any of them. BFS emits a whole level
40- before it opens the next one. The Rev variants expand the children, or the
41- elements of a level, in reverse order. This avoids a ` reverse ` , and was faster
42- on the binary and 10-ary trees in the benchmarks below.
43-
44- | Order | Open streams | Pending elements held |
45- | ----------| ------------------------------| ------------------------------------------------|
46- | DFS | one per level of the current path | none |
47- | wide DFS | one | unexpanded children of the nodes on the current path |
48- | BFS | one | the non-leaf elements of the next level |
49-
50- In a directory traversal an open stream is an open directory. DFS keeps one
51- file descriptor open for each directory on the current path. Wide DFS and BFS
52- keep one open, and read each directory from start to end before opening the
53- next one. Wide DFS holds memory proportional to the path, BFS to the widest
54- level.
37+ ### Example tree
38+
39+ The outputs below are for this tree. The children of each node are
40+ produced in the order shown. 5, 7, 8 and 9 are leaves.
41+
42+ ```
43+ 1
44+ |-- 2
45+ | |-- 4
46+ | | `-- 8
47+ | `-- 5
48+ `-- 3
49+ |-- 6
50+ | `-- 9
51+ `-- 7
52+ ```
53+
54+ ### Axes
55+
56+ Expanding a node means running the stream of its children. Every node is
57+ emitted exactly once. A serial traversal is described by four choices.
58+
59+ * Expansion order. The pending streams (the partly run streams and the
60+ children streams not yet started) are kept:
61+ * depth first: on a stack; the most recently added stream runs next.
62+ * breadth first: in a queue; the oldest stream runs next.
63+ * Batching:
64+ * interleaved: a stream yields one node and the children stream of
65+ that node is scheduled at once; the rest of the current stream is
66+ put back as pending. The children of different parents are
67+ interleaved in the output.
68+ * batched: a stream runs to completion before any other stream runs.
69+ All children of a node are emitted together.
70+ * Parent order:
71+ * pre: a node is emitted before its descendants.
72+ * post: a node is emitted after all its descendants. A leaf is
73+ emitted when it is produced, so the leaf children of a node come
74+ before its non-leaf children.
75+ * Sibling order, for batched traversals only. The children streams of
76+ the nodes of one batch are expanded:
77+ * forward: in the order the nodes were produced;
78+ * reverse: the last produced first.
79+
80+ An interleaved traversal expands a node before its later siblings have
81+ been produced, so the last sibling is not known yet and the sibling
82+ order cannot be reversed. Producing all the siblings first makes the
83+ traversal batched; read-ahead, described below, gives a third option.
84+
85+ The five orders of the Stream combinators are points on these axes. DFS
86+ is depth / interleaved / pre. Wide DFS is depth / batched / pre: it goes
87+ depth first along a path, but emits all the children of a node before it
88+ descends into any of them. BFS is breadth / batched / pre: it emits a
89+ whole level before it opens the next one. The Rev variants of wide DFS
90+ and BFS use the reverse sibling order. This avoids a ` reverse ` , and was
91+ faster on the binary and 10-ary trees in the benchmarks below.
92+
93+ ### Orders
94+
95+ | Expansion | Batching | Parent | Siblings | Output | Streamly |
96+ | ---| ---| ---| ---| ---| ---|
97+ | depth | interleaved | pre | - | 1 2 4 8 5 3 6 9 7 | ` concatIterate ` , ` unfoldIterateMaybe ` , ` StreamK.concatIterateWith append ` |
98+ | depth | interleaved | post | - | 8 4 5 2 9 6 7 3 1 | none |
99+ | depth | batched | pre | forward | 1 2 3 4 5 8 6 7 9 | ` wideDfsConcatIterate ` , ` wideDfsUnfoldIterate ` |
100+ | depth | batched | pre | reverse | 1 2 3 6 7 9 4 5 8 | ` wideDfsConcatIterateRev ` , ` wideDfsUnfoldIterateRev ` |
101+ | depth | batched | post | forward | 5 8 4 2 7 9 6 3 1 | none |
102+ | depth | batched | post | reverse | 7 9 6 3 5 8 4 2 1 | none |
103+ | breadth | interleaved | pre | - | 1 2 3 4 6 5 8 7 9 | none |
104+ | breadth | interleaved | post | - | 5 8 4 2 7 9 6 3 1 | none |
105+ | breadth | batched | pre | forward | 1 2 3 4 5 6 7 8 9 | ` bfsConcatIterate ` , ` bfsUnfoldIterateMaybe ` |
106+ | breadth | batched | pre | reverse | 1 2 3 6 7 4 5 8 9 | ` bfsConcatIterateRev ` , ` bfsUnfoldIterateRev ` |
107+ | breadth | batched | post | forward | 5 7 8 9 4 6 2 3 1 | none |
108+ | breadth | batched | post | reverse | 7 5 8 9 4 6 3 2 1 | none |
109+
110+ The outputs were computed with a model of the rules in Axes and agree
111+ with the streamly code of the listed combinators. Each Stream
112+ combinator ` xConcatIterate ` should have a fused ` xUnfoldIterate `
113+ counterpart that gives the same order.
114+
115+ Notes on the rows:
116+
117+ * depth / interleaved / post is the order of GNU ` find -depth ` : the
118+ nodes in the order produced, each non-leaf node replaced by its
119+ subtree followed by the node itself.
120+ * depth / batched / post also emits every node after its descendants,
121+ the order ` rm -r ` needs, with one open stream. It emits the leaves of
122+ a node before descending into its non-leaf children, so the order
123+ differs from GNU ` find -depth ` .
124+ * breadth / interleaved / pre is not a level order. On a tree in which
125+ node 2 has a chain 4 -> 5 -> 6 -> 7 and node 3 has the leaves 31 to
126+ 36, it emits 1 2 3 4 31 5 32 6 33 7 34 35 36: one node from each
127+ pending stream in turn. The level order emits 31 to 36 before 5, 6
128+ and 7.
129+ * ` StreamK.concatIterateWith interleave ` does not give the breadth /
130+ interleaved order. It nests ` interleave ` to the right, so the first
131+ stream gets every second turn, the second every fourth, and so on. On
132+ the example tree it gives 1 2 3 4 6 5 7 8 9; the queue gives
133+ 1 2 3 4 6 5 8 7 9. On the chain tree above both give the same output.
134+ * breadth / interleaved / post gives the same output as depth / batched
135+ / post on the example tree. On larger trees they differ. It needs,
136+ for each non-leaf node, a flag for the end of its children stream and
137+ a count of its non-leaf children not yet emitted.
138+ * breadth / batched / reverse expands each level in the reverse of the
139+ order in which the previous level was emitted. Compared with the
140+ forward order, depth 2 is reversed (6 7 4 5 instead of 4 5 6 7) and
141+ depth 3 is forward (8 9).
142+ * breadth / batched / post emits the leaves of each level as they are
143+ produced, then the non-leaf nodes level by level from the deepest,
144+ each level in the order its nodes were expanded.
145+
146+ ### Resources
147+
148+ | Expansion | Batching | Open streams | Memory |
149+ | ---| ---| ---| ---|
150+ | depth | interleaved | one for each node on the current path | the open streams |
151+ | depth | batched | 1 | the unexpanded non-leaf children of the nodes on the current path |
152+ | breadth | interleaved | every partly run stream in the queue, up to the width of the tree | the queue |
153+ | breadth | batched | 1 | the non-leaf nodes of the next level |
154+
155+ Post order adds:
156+
157+ * depth first: the non-leaf nodes on the current path, waiting to be
158+ emitted;
159+ * breadth / interleaved: the non-leaf nodes with unfinished
160+ descendants, with their counts;
161+ * breadth / batched: every non-leaf node, until the deepest level has
162+ been expanded.
163+
164+ In a directory traversal an open stream is an open directory, and the
165+ number of open streams is limited by the open file limit, which is
166+ usually much smaller than the memory available for holding entries. DFS
167+ keeps one file descriptor open for each directory on the current path
168+ and can exceed the limit on a deep tree; breadth / interleaved can
169+ exceed it on a wide tree. Wide DFS and BFS keep one open, and read each
170+ directory from start to end before opening the next one. Wide DFS holds
171+ memory proportional to the path, BFS to the widest level.
172+
173+ ### Read-ahead
174+
175+ An interleaved traversal can read each children stream completely into
176+ memory when it first runs, then emit from memory. The output order does
177+ not change. One stream is open at a time, and the memory is that of the
178+ batched traversal with the same expansion order. Because all the
179+ siblings are in memory before any of them is expanded, the siblings can
180+ also be reversed or sorted.
181+
182+ glibc ` fts ` works this way: ` fts_build ` reads a whole directory,
183+ optionally sorts the entries with the ` compar ` function, closes the
184+ directory, and then visits the entries depth first. It reports each
185+ directory twice, before its contents (` FTS_D ` ) and after them
186+ (` FTS_DP ` ), so one traversal supports both a pre-order action and a
187+ post-order action.
188+
189+ Proposed additions:
190+
191+ * A read-ahead option for the interleaved combinators. Without it,
192+ ` concatIterate ` can be given an ` f ` that returns a stream reading the
193+ whole children stream into an array first, e.g. with
194+ ` Stream.concatEffect ` .
195+ * A "pre and post" value of the parent order axis: a non-leaf node is
196+ emitted twice, tagged, before and after its descendants, as with the
197+ ` Enter ` and ` Exit ` events in Expressiveness and gaps.
198+
199+ ### Iterative deepening
200+
201+ Iterative deepening runs depth / interleaved / pre repeatedly with
202+ depth limits 1, 2, 3, and so on, and emits only the nodes at the limit
203+ depth in each run. The output is the breadth / batched / pre / forward
204+ order. The open streams are those of depth first, one for each node on
205+ the current path, and no level is held in memory, but a node at depth d
206+ is expanded once for each depth limit greater than d. There is no
207+ combinator; it can be built from ` concatIterate ` with a depth limit.
55208
56209## Marking the leaves: Maybe
57210
@@ -226,8 +379,10 @@ concatIterateWith combine f = iterateStream
226379```
227380
228381` mergeIterateWith ` uses ` mergeMapWith ` instead, which combines the streams
229- pairwise, as a balanced tree. With ` interleave ` this gives a balanced
230- traversal of the tree.
382+ pairwise, as a balanced tree. With ` interleave ` , when every node has 2 or 4
383+ children, the nodes of each level are emitted together, in a different order
384+ from BFS. With other numbers of children, or an unbalanced tree, nodes of the
385+ next level are emitted before the current level ends.
231386
232387In these forms the traversal order is decided by the combine function, not by
233388the combinator name. They are CPS streams and do not fuse. They are the
@@ -392,14 +547,21 @@ element. Every stream is split at every element, so any idle worker can pick
392547up the rest of any stream. Each split is a queue operation shared between
393548threads, which is why chunked elements help most in the concurrent case.
394549
395- The configuration decides the order :
550+ The configuration selects the work queue :
396551
397- - default: the work queue is LIFO, and results are emitted as they are
398- produced;
399- - ` interleaved True ` : the work queue is FIFO, and streams are scheduled round
400- robin;
401- - ` ordered True ` : the output is in the order of the serial DFS;
402- - ` maxThreads n ` and ` maxBuffer n ` limit the workers and the buffered results.
552+ - default: a LIFO queue (` enqueueLIFO ` in ` Channel/Append.hs ` ); results are
553+ emitted as they are produced;
554+ - ` interleaved True ` : a FIFO queue (` enqueueFIFO ` in
555+ ` Channel/Interleave.hs ` ); streams are scheduled round robin;
556+ - ` ordered True ` : a LIFO queue, with the output reordered into the serial DFS
557+ order (` enqueueAhead ` in ` Channel/Append.hs ` );
558+ - ` maxThreads n ` and ` maxBuffer n ` limit the workers and the buffered
559+ results. These and the other options (` eager ` , rate) change performance,
560+ not the order.
561+
562+ The comment "The channel q should be FIFO for DFS, otherwise it is BFS" in
563+ ` parConcatIterate ` has FIFO and LIFO the other way round: with one worker the
564+ LIFO queue gives the depth / interleaved / pre order.
403565
404566` ListDir.hs ` from streamly-examples, one directory tree, hot caches. These
405567numbers are from a separate measurement, not the one in the chunked table:
@@ -433,12 +595,74 @@ The MB column is the allocation. With `-N2` the times were 3 to 10 percent
433595lower with ` Nothing ` . The ` FileSystem.DirIO ` benchmark showed no difference:
434596its tree has 3906 directories and no files, so no node is a leaf.
435597
598+ ### Parallel orders
599+
600+ A parallel traversal has the four axes of a serial traversal, with the
601+ expansion order and batching describing how the work queue is scheduled, and
602+ one more axis:
603+
604+ * Output:
605+ * unordered: each node is emitted as soon as it is produced. With one
606+ worker (` maxThreads 1 ` ) the output is the order of the serial
607+ traversal; with more workers the order is not deterministic. Post
608+ order still guarantees that a node is emitted after all its
609+ descendants.
610+ * ordered: the output is the order of the serial traversal for any
611+ number of workers. The workers run streams ahead of the consumer.
612+
613+ Each row is the parallel version of the serial traversal with the same
614+ expansion, batching and parent order; the output orders are those of the
615+ serial table. The batched rows cover both sibling orders.
616+
617+ | Expansion | Batching | Parent | Unordered | Ordered |
618+ | ---| ---| ---| ---| ---|
619+ | depth | interleaved | pre | ` parConcatIterate id ` | ` parConcatIterate (ordered True) ` |
620+ | depth | interleaved | post | none | none |
621+ | depth | batched | pre | none | none |
622+ | depth | batched | post | none | none |
623+ | breadth | interleaved | pre | ` parConcatIterate (interleaved True) ` | none |
624+ | breadth | interleaved | post | none | none |
625+ | breadth | batched | pre | none; a level loop with ` parConcatMap ` | none; a level loop with ` parConcatMap (ordered True) ` |
626+ | breadth | batched | post | none | none |
627+
628+ The three ` parConcatIterate ` rows were run on the example tree with one
629+ worker and gave the serial outputs. With several workers they gave the same
630+ outputs, but the tree is too small for the workers to overlap, so this does
631+ not test the orders under real concurrency.
632+
633+ A level loop runs ` parConcatMap ` over the non-leaf nodes of one level,
634+ collects the next level, and repeats. Each level waits for the previous one to
635+ finish. A channel whose work items are whole streams, each run to completion
636+ by one worker, with a LIFO or FIFO queue, would give depth / batched and
637+ breadth / batched without waiting at each level.
638+
639+ Resources:
640+
641+ * LIFO queue, unordered: open streams are the partly run streams on the
642+ queue and those being run by the workers.
643+ * FIFO queue, unordered: open streams are all partly run streams on the
644+ queue, which can exceed the open file limit on a wide tree.
645+ * Level loop: one open stream per worker; one level in memory.
646+ * Ordered: in addition, the output produced ahead of the consumer.
647+
648+ For an ordered traversal the schedule affects only which streams are run
649+ ahead of the output, not the output order.
650+
651+ Unordered post order is the order a parallel ` rm -r ` or ` du ` needs: a node is
652+ emitted after all its descendants, but the nodes of different subtrees may be
653+ emitted in any order. It needs the same per-node state as breadth /
654+ interleaved / post.
655+
436656Not implemented yet:
437657
438658- ` parMergeIterate ` , the concurrent ` mergeIterateWith ` , is declared but is
439659 ` undefined ` .
440660- Concurrent BFS or wide DFS with a guaranteed order. That needs a barrier
441- between levels.
661+ between levels, or the channel of whole streams described above.
662+ - Work stealing: each worker keeps its own LIFO queue, and an idle worker
663+ takes the oldest stream from another worker's queue. It gives the same
664+ order guarantees as the LIFO queue, with less contention on a shared queue.
665+ It would be a new channel type.
442666
443667## Bottom-up reduction
444668
@@ -526,6 +750,34 @@ Proposed changes:
526750 ` XXX ` note on it suggests, by analogy with ` mapMAccum ` .
527751* ** An ` Either ` form for unfolds** , if added, should be ` unfoldIterateLefts ` ,
528752 matching ` concatIterateLeftsWith ` .
753+ * ** Names from the traversal axes.** The current names mix two schemes:
754+ ` concatIterate ` for depth first, ` bfs ` and ` wideDfs ` prefixes for the
755+ others. Proposed: a ` bfs ` prefix for breadth first (depth first has no
756+ prefix), and the suffixes ` Batch ` , ` Post ` and ` Rev ` , in that order, for the
757+ values that are not the default (interleaved, pre, forward).
758+
759+ | Expansion | Batching | Parent | Proposed | Current |
760+ | ---| ---| ---| ---| ---|
761+ | depth | interleaved | pre | ` concatIterate ` | ` concatIterate ` |
762+ | depth | interleaved | post | ` concatIteratePost ` | none |
763+ | depth | batched | pre | ` concatIterateBatch[Rev] ` | ` wideDfsConcatIterate[Rev] ` |
764+ | depth | batched | post | ` concatIterateBatchPost[Rev] ` | none |
765+ | breadth | interleaved | pre | ` bfsConcatIterate ` | none |
766+ | breadth | interleaved | post | ` bfsConcatIteratePost ` | none |
767+ | breadth | batched | pre | ` bfsConcatIterateBatch[Rev] ` | ` bfsConcatIterate[Rev] ` |
768+ | breadth | batched | post | ` bfsConcatIterateBatchPost[Rev] ` | none |
769+
770+ The fused versions replace ` ConcatIterate ` with ` UnfoldIterate ` , and the
771+ parallel versions add the ` par ` prefix.
772+
773+ Under this scheme ` bfsConcatIterate ` changes from breadth / batched to
774+ breadth / interleaved. Code using the old name would compile and give a
775+ different order, so the old name has to be deprecated for at least one
776+ release before it is reused.
777+
778+ The alternative is a ` wide ` prefix for batched instead of the ` Batch `
779+ suffix: ` wideDfsConcatIterate ` stays, and breadth / batched becomes
780+ ` wideBfsConcatIterate ` .
529781
530782The primitive forms are not provided as separate ` Stream ` combinators. They
531783are the ` Maybe ` forms applied to ` Just ` , and the ` Just ` is removed after
@@ -588,6 +840,11 @@ Gaps:
588840 increase along a path need a priority queue traversal.
589841* ** Concurrent BFS and wide DFS with a guaranteed order** , and
590842 ` parMergeIterate ` . Not implemented.
843+ * ** Post order and breadth / interleaved order.** No combinator gives a
844+ post order or the breadth / interleaved order; the rows marked "none" in
845+ the order tables.
846+ * ** Diagonal interleaving.** A tree version of ` StreamK.fairConcatFor ` , e.g.
847+ ` fairConcatIterate ` . Not implemented; its order is not worked out yet.
591848* ** Fixpoint iteration in general** , applying a stream transformation
592849 ` Stream m a -> Stream m a ` until the output does not change. Only the level
593850 at a time form is covered, by ` concatIterateScan ` . The general form is
0 commit comments