Skip to content

Commit 866731c

Browse files
committed
All forms of IO composition are now stack-safe
- sequencing large (non-infinite!) iterables of IOs will eagerly fold all IOs into a single IO that can parallelize every step
1 parent 9c944e5 commit 866731c

3 files changed

Lines changed: 160 additions & 121 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/).
77
### Changed
88
- `MonadT` is now witnessed by a parameter for better subtyping
99
- `Alter` now merely requires an `Fn1` instead of an explicit `Effect`
10+
- `IO` now internally trampolines all forms of composition, including lazyZip;
11+
sequencing very large iterables of IO will work, if you have the heap, and
12+
retain parallelization inflection points
1013

1114
### Added
1215
- `Optic#andThen`, `Optic#compose`, and other defaults added

‎src/main/java/com/jnape/palatable/lambda/io/IO.java‎

Lines changed: 48 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,24 @@
44
import com.jnape.palatable.lambda.adt.Try;
55
import com.jnape.palatable.lambda.adt.Unit;
66
import com.jnape.palatable.lambda.adt.choice.Choice2;
7-
import com.jnape.palatable.lambda.adt.hlist.Tuple2;
87
import com.jnape.palatable.lambda.functions.Fn0;
98
import com.jnape.palatable.lambda.functions.Fn1;
9+
import com.jnape.palatable.lambda.functions.builtin.fn2.LazyRec;
1010
import com.jnape.palatable.lambda.functions.specialized.SideEffect;
1111
import com.jnape.palatable.lambda.functor.Applicative;
12+
import com.jnape.palatable.lambda.functor.Functor;
1213
import com.jnape.palatable.lambda.functor.builtin.Lazy;
1314
import com.jnape.palatable.lambda.monad.Monad;
1415

15-
import java.util.LinkedList;
1616
import java.util.concurrent.CompletableFuture;
1717
import java.util.concurrent.Executor;
1818

1919
import static com.jnape.palatable.lambda.adt.Unit.UNIT;
2020
import static com.jnape.palatable.lambda.adt.choice.Choice2.a;
21-
import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
2221
import static com.jnape.palatable.lambda.functions.Fn0.fn0;
2322
import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly;
24-
import static com.jnape.palatable.lambda.functions.builtin.fn2.Into.into;
25-
import static com.jnape.palatable.lambda.functions.builtin.fn3.FoldLeft.foldLeft;
26-
import static com.jnape.palatable.lambda.functions.recursion.RecursiveResult.recurse;
27-
import static com.jnape.palatable.lambda.functions.recursion.RecursiveResult.terminate;
28-
import static com.jnape.palatable.lambda.functions.recursion.Trampoline.trampoline;
23+
import static com.jnape.palatable.lambda.functions.builtin.fn1.Downcast.downcast;
24+
import static com.jnape.palatable.lambda.functor.builtin.Lazy.lazy;
2925
import static com.jnape.palatable.lambda.monad.Monad.join;
3026
import static java.util.concurrent.CompletableFuture.completedFuture;
3127
import static java.util.concurrent.CompletableFuture.supplyAsync;
@@ -142,20 +138,16 @@ public final <B> IO<B> fmap(Fn1<? super A, ? extends B> fn) {
142138
* {@inheritDoc}
143139
*/
144140
@Override
145-
public final <B> IO<B> zip(Applicative<Fn1<? super A, ? extends B>, IO<?>> appFn) {
146-
@SuppressWarnings("unchecked")
147-
IO<Object> source = (IO<Object>) this;
148-
@SuppressWarnings("unchecked")
149-
IO<Fn1<Object, Object>> zip = (IO<Fn1<Object, Object>>) (Object) appFn;
150-
return new Compose<>(source, a(zip));
141+
public <B> IO<B> zip(Applicative<Fn1<? super A, ? extends B>, IO<?>> appFn) {
142+
return new Compose<>(this, a((IO<Fn1<? super A, ? extends B>>) appFn));
151143
}
152144

153145
/**
154146
* {@inheritDoc}
155147
*/
156148
@Override
157-
public <B> Lazy<IO<B>> lazyZip(Lazy<? extends Applicative<Fn1<? super A, ? extends B>, IO<?>>> lazyAppFn) {
158-
return Monad.super.lazyZip(lazyAppFn).fmap(Monad<B, IO<?>>::coerce);
149+
public final <B> Lazy<IO<B>> lazyZip(Lazy<? extends Applicative<Fn1<? super A, ? extends B>, IO<?>>> lazyAppFn) {
150+
return Monad.super.lazyZip(lazyAppFn).<IO<B>>fmap(Functor::coerce).coerce();
159151
}
160152

161153
/**
@@ -179,11 +171,9 @@ public final <B> IO<A> discardR(Applicative<B, IO<?>> appB) {
179171
*/
180172
@Override
181173
public final <B> IO<B> flatMap(Fn1<? super A, ? extends Monad<B, IO<?>>> f) {
182-
@SuppressWarnings("unchecked")
183-
IO<Object> source = (IO<Object>) this;
184174
@SuppressWarnings({"unchecked", "RedundantCast"})
185-
Fn1<Object, IO<Object>> flatMap = (Fn1<Object, IO<Object>>) (Object) f;
186-
return new Compose<>(source, Choice2.b(flatMap));
175+
Choice2<IO<?>, Fn1<Object, IO<?>>> composition = Choice2.b((Fn1<Object, IO<?>>) (Object) f);
176+
return new Compose<>(this, composition);
187177
}
188178

189179
/**
@@ -279,61 +269,55 @@ public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) {
279269
}
280270

281271
private static final class Compose<A> extends IO<A> {
282-
private final IO<Object> source;
283-
private final Choice2<IO<Fn1<Object, Object>>, Fn1<Object, IO<Object>>> composition;
284272

285-
private Compose(IO<Object> source, Choice2<IO<Fn1<Object, Object>>, Fn1<Object, IO<Object>>> composition) {
273+
private final IO<?> source;
274+
private final Choice2<IO<?>, Fn1<Object, IO<?>>> composition;
275+
276+
private Compose(IO<?> source, Choice2<IO<?>, Fn1<Object, IO<?>>> composition) {
286277
this.source = source;
287278
this.composition = composition;
288279
}
289280

290281
@Override
291282
public A unsafePerformIO() {
292-
@SuppressWarnings("unchecked")
293-
A result = (A) trampoline(into((source, compositions) -> {
294-
Object res = source.unsafePerformIO();
295-
return compositions.isEmpty()
296-
? terminate(res)
297-
: compositions.pop().match(
298-
zip -> recurse(tuple(io(zip.unsafePerformIO().apply(res)), compositions)),
299-
flatMap -> {
300-
IO<Object> next = flatMap.apply(res);
301-
return (next instanceof Compose<?>)
302-
? recurse(((Compose<?>) next).deforest(compositions))
303-
: recurse(tuple(next, compositions));
304-
});
305-
}), deforest(new LinkedList<>()));
306-
307-
return result;
283+
Lazy<Object> lazyA = LazyRec.<IO<?>, Object>lazyRec(
284+
(f, io) -> {
285+
if (io instanceof IO.Compose<?>) {
286+
Compose<?> compose = (Compose<?>) io;
287+
Lazy<Object> head = f.apply(compose.source);
288+
return compose.composition
289+
.match(zip -> head.flatMap(x -> f.apply(zip)
290+
.<Fn1<Object, Object>>fmap(downcast())
291+
.fmap(g -> g.apply(x))),
292+
flatMap -> head.fmap(flatMap).flatMap(f));
293+
}
294+
return lazy(io::unsafePerformIO);
295+
},
296+
this);
297+
return downcast(lazyA.value());
308298
}
309299

310300
@Override
301+
@SuppressWarnings("unchecked")
311302
public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) {
312-
@SuppressWarnings("unchecked")
313-
CompletableFuture<A> future = (CompletableFuture<A>) deforest(new LinkedList<>())
314-
.into((source, compositions) -> foldLeft(
315-
(ioFuture, composition) -> composition
316-
.match(zip -> zip.unsafePerformAsyncIO(executor)
317-
.thenComposeAsync(f -> ioFuture.thenApply(f.toFunction()), executor),
318-
flatMap -> ioFuture.thenComposeAsync(obj -> flatMap.apply(obj)
319-
.unsafePerformAsyncIO(executor), executor)),
320-
source.unsafePerformAsyncIO(executor),
321-
compositions));
322-
return future;
323-
}
324-
325-
private Tuple2<IO<Object>, LinkedList<Choice2<IO<Fn1<Object, Object>>, Fn1<Object, IO<Object>>>>>
326-
deforest(LinkedList<Choice2<IO<Fn1<Object, Object>>, Fn1<Object, IO<Object>>>> branches) {
327-
Tuple2<Compose<?>, LinkedList<Choice2<IO<Fn1<Object, Object>>, Fn1<Object, IO<Object>>>>> args =
328-
tuple(this, branches);
329-
return trampoline(into((source, compositions) -> {
330-
IO<Object> leaf = source.source;
331-
compositions.push(source.composition);
332-
return leaf instanceof Compose<?>
333-
? recurse(tuple((Compose<?>) leaf, compositions))
334-
: terminate(tuple(leaf, compositions));
335-
}), args);
303+
Lazy<CompletableFuture<Object>> lazyFuture = LazyRec.<IO<?>, CompletableFuture<Object>>lazyRec(
304+
(f, io) -> {
305+
if (io instanceof IO.Compose<?>) {
306+
Compose<?> compose = (Compose<?>) io;
307+
Lazy<CompletableFuture<Object>> head = f.apply(compose.source);
308+
return compose.composition
309+
.match(zip -> head.flatMap(futureX -> f.apply(zip)
310+
.fmap(futureF -> futureF.thenCompose(f2 -> futureX
311+
.thenApply(((Fn1<Object, Object>) f2).toFunction())))),
312+
flatMap -> head.fmap(futureX -> futureX
313+
.thenComposeAsync(x -> f.apply(flatMap.apply(x)).value(),
314+
executor)));
315+
}
316+
return lazy(() -> (CompletableFuture<Object>) io.unsafePerformAsyncIO(executor));
317+
},
318+
this);
319+
320+
return (CompletableFuture<A>) lazyFuture.value();
336321
}
337-
338322
}
339323
}

‎src/test/java/com/jnape/palatable/lambda/io/IOTest.java‎

Lines changed: 109 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.jnape.palatable.lambda.io;
22

3+
import com.jnape.palatable.lambda.adt.Unit;
34
import com.jnape.palatable.lambda.adt.hlist.Tuple2;
45
import com.jnape.palatable.lambda.functions.Fn1;
6+
import com.jnape.palatable.lambda.functions.builtin.fn2.Sequence;
57
import com.jnape.palatable.traitor.annotations.TestTraits;
68
import com.jnape.palatable.traitor.runners.Traits;
79
import org.junit.Test;
@@ -21,13 +23,17 @@
2123
import static com.jnape.palatable.lambda.adt.Either.left;
2224
import static com.jnape.palatable.lambda.adt.Either.right;
2325
import static com.jnape.palatable.lambda.adt.Unit.UNIT;
26+
import static com.jnape.palatable.lambda.functions.builtin.fn1.Size.size;
27+
import static com.jnape.palatable.lambda.functions.builtin.fn2.Replicate.replicate;
2428
import static com.jnape.palatable.lambda.functions.builtin.fn2.Tupler2.tupler;
2529
import static com.jnape.palatable.lambda.functions.builtin.fn3.Times.times;
30+
import static com.jnape.palatable.lambda.functor.builtin.Lazy.lazy;
2631
import static com.jnape.palatable.lambda.io.IO.externallyManaged;
2732
import static com.jnape.palatable.lambda.io.IO.io;
2833
import static java.util.concurrent.CompletableFuture.completedFuture;
2934
import static java.util.concurrent.Executors.newFixedThreadPool;
3035
import static java.util.concurrent.ForkJoinPool.commonPool;
36+
import static java.util.concurrent.TimeUnit.MILLISECONDS;
3137
import static org.junit.Assert.assertArrayEquals;
3238
import static org.junit.Assert.assertEquals;
3339
import static org.junit.Assert.fail;
@@ -126,63 +132,6 @@ public void exceptionallyRescuesFutures() {
126132
assertEquals("foo", externallyManaged.unsafePerformIO());
127133
}
128134

129-
@Test
130-
public void linearSyncStackSafety() {
131-
assertEquals(STACK_EXPLODING_NUMBER,
132-
times(STACK_EXPLODING_NUMBER, f -> f.fmap(x -> x + 1), io(0)).unsafePerformIO());
133-
assertEquals(STACK_EXPLODING_NUMBER,
134-
times(STACK_EXPLODING_NUMBER, f -> f.zip(f.pure(x -> x + 1)), io(0)).unsafePerformIO());
135-
assertEquals((Integer) 0,
136-
times(STACK_EXPLODING_NUMBER, f -> f.pure(0).discardR(f), io(0)).unsafePerformIO());
137-
assertEquals((Integer) 1,
138-
times(STACK_EXPLODING_NUMBER, f -> f.pure(1).discardR(f), io(0)).unsafePerformIO());
139-
assertEquals((Integer) 0,
140-
times(STACK_EXPLODING_NUMBER, f -> f.pure(1).discardL(f), io(0)).unsafePerformIO());
141-
assertEquals(STACK_EXPLODING_NUMBER,
142-
times(STACK_EXPLODING_NUMBER, f -> f.flatMap(x -> f.pure(x + 1)), io(0)).unsafePerformIO());
143-
}
144-
145-
@Test
146-
public void recursiveSyncFlatMapStackSafety() {
147-
assertEquals(STACK_EXPLODING_NUMBER,
148-
new Fn1<IO<Integer>, IO<Integer>>() {
149-
@Override
150-
public IO<Integer> checkedApply(IO<Integer> a) {
151-
return a.flatMap(x -> x < STACK_EXPLODING_NUMBER ? apply(io(x + 1)) : io(x));
152-
}
153-
}.apply(io(0)).unsafePerformIO());
154-
155-
}
156-
157-
@Test
158-
public void linearAsyncStackSafety() {
159-
assertEquals(STACK_EXPLODING_NUMBER,
160-
times(STACK_EXPLODING_NUMBER, f -> f.fmap(x -> x + 1), io(0)).unsafePerformAsyncIO().join());
161-
assertEquals(STACK_EXPLODING_NUMBER,
162-
times(STACK_EXPLODING_NUMBER, f -> f.zip(f.pure(x -> x + 1)), io(0)).unsafePerformAsyncIO()
163-
.join());
164-
assertEquals((Integer) 0,
165-
times(STACK_EXPLODING_NUMBER, f -> f.pure(0).discardR(f), io(0)).unsafePerformAsyncIO().join());
166-
assertEquals((Integer) 1,
167-
times(STACK_EXPLODING_NUMBER, f -> f.pure(1).discardR(f), io(0)).unsafePerformAsyncIO().join());
168-
assertEquals((Integer) 0,
169-
times(STACK_EXPLODING_NUMBER, f -> f.pure(1).discardL(f), io(0)).unsafePerformAsyncIO().join());
170-
assertEquals(STACK_EXPLODING_NUMBER,
171-
times(STACK_EXPLODING_NUMBER, f -> f.flatMap(x -> f.pure(x + 1)), io(0)).unsafePerformAsyncIO()
172-
.join());
173-
}
174-
175-
@Test
176-
public void recursiveAsyncFlatMapStackSafety() {
177-
assertEquals(STACK_EXPLODING_NUMBER,
178-
new Fn1<IO<Integer>, IO<Integer>>() {
179-
@Override
180-
public IO<Integer> checkedApply(IO<Integer> a) {
181-
return a.flatMap(x -> x < STACK_EXPLODING_NUMBER ? apply(io(x + 1)) : io(x));
182-
}
183-
}.apply(io(0)).unsafePerformAsyncIO().join());
184-
}
185-
186135
@Test
187136
public void safe() {
188137
assertEquals(right(1), io(() -> 1).safe().unsafePerformIO());
@@ -243,4 +192,107 @@ public void throwing() {
243192
assertEquals(expected, actual);
244193
}
245194
}
195+
196+
@Test
197+
public void zipStackSafety() {
198+
IO<Fn1<? super Integer, ? extends Integer>> zipAdd1 = io(x -> x + 1);
199+
IO<Integer> zero = io(0);
200+
201+
IO<Integer> leftHeavy = times(STACK_EXPLODING_NUMBER, io -> io.zip(zipAdd1), zero);
202+
assertEquals(STACK_EXPLODING_NUMBER, leftHeavy.unsafePerformIO());
203+
assertEquals(STACK_EXPLODING_NUMBER, leftHeavy.unsafePerformAsyncIO().join());
204+
205+
IO<Integer> rightHeavy = times(STACK_EXPLODING_NUMBER, io -> zipAdd1.zip(io.fmap(x -> f -> f.apply(x))), zero);
206+
assertEquals(STACK_EXPLODING_NUMBER, rightHeavy.unsafePerformIO());
207+
assertEquals(STACK_EXPLODING_NUMBER, rightHeavy.unsafePerformAsyncIO().join());
208+
}
209+
210+
@Test
211+
public void discardStackSafety() {
212+
IO<Integer> discardL = times(STACK_EXPLODING_NUMBER, io -> io(1).discardL(io), io(0));
213+
assertEquals((Integer) 0, discardL.unsafePerformIO());
214+
assertEquals((Integer) 0, discardL.unsafePerformAsyncIO().join());
215+
216+
IO<Integer> discardR = times(STACK_EXPLODING_NUMBER, io -> io.discardR(io(1)), io(0));
217+
assertEquals((Integer) 0, discardR.unsafePerformIO());
218+
assertEquals((Integer) 0, discardR.unsafePerformAsyncIO().join());
219+
}
220+
221+
@Test
222+
public void lazyZipStackSafety() {
223+
IO<Fn1<? super Integer, ? extends Integer>> zipAdd1 = io(x -> x + 1);
224+
IO<Integer> zero = io(0);
225+
226+
IO<Integer> leftHeavy = times(STACK_EXPLODING_NUMBER, io -> io.lazyZip(lazy(zipAdd1)).value(), zero);
227+
assertEquals(STACK_EXPLODING_NUMBER, leftHeavy.unsafePerformIO());
228+
assertEquals(STACK_EXPLODING_NUMBER, leftHeavy.unsafePerformAsyncIO().join());
229+
230+
IO<Integer> rightHeavy = times(STACK_EXPLODING_NUMBER,
231+
io -> zipAdd1.<Integer>lazyZip(lazy(io.fmap(x -> f -> f.apply(x)))).value(),
232+
zero);
233+
assertEquals(STACK_EXPLODING_NUMBER, rightHeavy.unsafePerformIO());
234+
assertEquals(STACK_EXPLODING_NUMBER, rightHeavy.unsafePerformAsyncIO().join());
235+
}
236+
237+
@Test
238+
public void flatMapStackSafety() {
239+
Fn1<Integer, IO<Integer>> add1 = x -> io(() -> x + 1);
240+
IO<Integer> zero = io(0);
241+
242+
IO<Integer> leftHeavy = times(STACK_EXPLODING_NUMBER, io -> io.flatMap(add1), zero);
243+
assertEquals(STACK_EXPLODING_NUMBER, leftHeavy.unsafePerformIO());
244+
assertEquals(STACK_EXPLODING_NUMBER, leftHeavy.unsafePerformAsyncIO().join());
245+
246+
IO<Integer> rightHeavy = times(STACK_EXPLODING_NUMBER,
247+
io -> add1.apply(0).flatMap(x -> io.fmap(y -> x + y)),
248+
zero);
249+
assertEquals(STACK_EXPLODING_NUMBER, rightHeavy.unsafePerformIO());
250+
assertEquals(STACK_EXPLODING_NUMBER, rightHeavy.unsafePerformAsyncIO().join());
251+
}
252+
253+
@Test
254+
public void staggeredZipAndFlatMapStackSafety() {
255+
assertEquals(STACK_EXPLODING_NUMBER,
256+
times(STACK_EXPLODING_NUMBER, io -> io.<Integer>zip(io(x -> x + 1))
257+
.flatMap(x -> io(() -> x))
258+
.zip(io(x -> x)), io(0))
259+
.unsafePerformIO());
260+
}
261+
262+
@Test
263+
public void sequenceStackSafety() {
264+
assertEquals(STACK_EXPLODING_NUMBER,
265+
Sequence.sequence(replicate(STACK_EXPLODING_NUMBER, io(UNIT)), IO::io)
266+
.fmap(size())
267+
.fmap(Long::intValue)
268+
.unsafePerformIO());
269+
270+
assertEquals(STACK_EXPLODING_NUMBER,
271+
Sequence.sequence(replicate(STACK_EXPLODING_NUMBER, io(UNIT)), IO::io)
272+
.fmap(size())
273+
.fmap(Long::intValue)
274+
.unsafePerformAsyncIO().join());
275+
}
276+
277+
@Test
278+
public void sequenceIOExecutesInParallel() {
279+
int n = 2;
280+
CountDownLatch latch = new CountDownLatch(n);
281+
Sequence.sequence(replicate(n, io(() -> {
282+
latch.countDown();
283+
if (!latch.await(100, MILLISECONDS)) {
284+
throw new AssertionError("Expected latch to countDown in time, but didn't.");
285+
}
286+
})), IO::io)
287+
.unsafePerformAsyncIO()
288+
.join();
289+
}
290+
291+
@Test
292+
public void sequenceIsRepeatable() {
293+
IO<Iterable<Unit>> io = Sequence.sequence(replicate(3, io(UNIT)), IO::io);
294+
295+
assertEquals((Long) 3L, size(io.unsafePerformIO()));
296+
assertEquals((Long) 3L, size(io.unsafePerformIO()));
297+
}
246298
}

0 commit comments

Comments
 (0)