I am trying to understand what's the correct way to handle errors using core.async/pipeline, my pipeline is the following:
input --> xf-run-computation --> first-out
first-out --> xf-run-computation --> last-out
Where xf-run-computation will do an http calls and return response. However some of these responses will return an error. What's the best way to handles these errors?
My solution is to split the outputs channels in success-values and error-values and then merge them back to a channel:
(let [[success-values1 error-values1] (split fn-to-split first-out)
[success-values2 error-values2] (split fn-to-split last-out)
errors (merge [error-values1 error-values2])]
(pipeline 4 first-out xf-run-computation input)
(pipeline 4 last-out xf-run-computation success-values1)
[last-out errors])
So my function will return the last results and the errors.
Generally speaking, what is "the" correct way is probably depending on your application needs, but given your problem description, I think there are three things you need to consider:
xf-run-computation returns data that your business logic would see as errors,
xf-run-computation throws an exception and
given that http calls are involved, some runs of xf-run-computation might never finish (or not finish in time).
Regarding point 3., the first thing you should consider is using pipeline-blocking instead of pipeline.
I think your question is mostly related to point 1. The basic idea is that the result of xf-run-computation needs to return a data structure (say a map or a record), which clearly marks a result as an error or a success, e.g. {:title nil :body nil :status "error"}. This will give you some options of dealing with the situation:
all your later code simply ignores input data which has :status "error". I.e., your xf-run-computation would contain a line like (when (not (= (:status input) "error")) (run-computation input)),
you could run a filter on all results between the pipeline-calls and filter them as needed (note that filter can also be used as a transducer in a pipeline, thereby obliterating the old filter> and filter< functions of core.async),
you use async/split like you suggested / Alan Thompson shows in his answer to to filter out the error values to a separate error channel. There is no real need to have a second error channel for your second pipeline if you're going to merge the values anyway, you can simply re-use your error channel.
For point 2., the problem is that any exception in xf-run-computation is happening in another thread and will not simply propagate back to your calling code. But you can make use of the ex-handler argument to pipeline (and pipeline-blocking). You could either simply filter out all exceptions, put the result on a separate exception channel or try to catch them and turn them into errors (potentially putting them back on the result or another error channel) -- the latter only makes sense, if the exception gives you enough information, e.g. an id or something that allows to tie back the exception to the input which caused the exception. You could arrange for this in xf-run-computation (i.e. catch any exception thrown from a third-party library like the http call).
For point 3, the canonical answer in core.async would be to point to a timeout channel, but this doesn't make much sense in relation to pipeline. A better idea is to ensure on your http calls that a timeout is set, e.g. the :timeout option of http-kit or :socket-timeout and :conn-timeout of clj-http. Note that these options will usually result in an exception on timeout.
Here is an example that does what you are suggesting. Beginning with (range 10) it first filters out the multiples of 5, then the multiples of 3.
(ns tst.clj.core
(:use clj.core
clojure.test )
(:require
[clojure.core.async :as async]
[clojure.string :as str]
)
)
(defn err-3 [x]
"'fail' for multiples of 3"
(if (zero? (mod x 3))
(+ x 300) ; error case
x)) ; non-error
(defn err-5 [x]
"'fail' for multiples of 5"
(if (zero? (mod x 5))
(+ x 500) ; error case
x)) ; non-error
(defn is-ok?
"Returns true if the value is not 'in error' (>=100)"
[x]
(< x 100))
(def ch-0 (async/to-chan (range 10)))
(def ch-1 (async/chan 99))
(def ch-2 (async/chan 99))
(deftest t-2
(let [
_ (async/pipeline 1 ch-1 (map err-5) ch-0)
[ok-chan-1 fail-chan-1] (async/split is-ok? ch-1 99 99)
_ (async/pipeline 1 ch-2 (map err-3) ok-chan-1)
[ok-chan-2 fail-chan-2] (async/split is-ok? ch-2 99 99)
ok-vec-2 (async/<!! (async/into [] ok-chan-2))
fail-vec-1 (async/<!! (async/into [] fail-chan-1))
fail-vec-2 (async/<!! (async/into [] fail-chan-2))
]
(is (= ok-vec-2 [1 2 4 7 8]))
(is (= fail-vec-1 [500 505]))
(is (= fail-vec-2 [303 306 309]))))
Rather than return the errors, I would probably just log them as soon as they are detected and then forget about them.
Related
Question
I would like to black hole print like behaviors within my test bodies in order to keep my log output looking clean and tidy.
(deftest some-test
(testing "something"
(logless
(is (= 22 (test-thing 14))))))
I expect test-thing to call println and other similar calls to *out* and would like those to stop polluting my test output.
Is there a recognized way to do this in general?
I found this guy (with-out-str) but it's capturing the string, not quite what I'm looking for.
Background
I'm fairly new to Clojure, coming largely from a javascript world. Having a blast so far! But there's lots left for me to learn.
In Clojure, not Clojure.script (if it matters)
Just use with-out-str and then ignore the string.
Note that this will not capture error messages or messages from Java libraries. If you want to capture and/or suppress this output, I have written 3 additional functions in the Tupelo library that you may find useful:
with-err-str
with-system-err-str
with-system-out-str
The code looks like this:
(defmacro with-system-err-str
"Evaluates exprs in a context in which JVM System/err is bound to a fresh
PrintStream. Returns the string created by any nested printing calls."
[& body]
`(let [baos# (ByteArrayOutputStream.)
ps# (PrintStream. baos#)]
(System/setErr ps#)
~#body
(System/setErr System/err)
(.close ps#)
(.toString baos#)))
If you wanted, you could make a new macro like so:
(defmacro with-printing-suppressed
"Evaluates exprs in a context in which JVM System/err and System/out captured & discarded."
[& body]
`(let [baos# (ByteArrayOutputStream.)
ps# (PrintStream. baos#)
s# (new java.io.StringWriter)]
(System/setErr ps#)
(System/setOut ps#)
(binding [*err* s#
*out* s#]
(let [result# (do ~#body)]
(.close ps#)
(System/setErr System/err)
(System/setOut System/out)
result#))))
(defn stuff []
(println "***** doing stuff *****")
42)
and then test it:
(println "calling - before")
(is= 42 (with-printing-suppressed
(stuff)))
(println "calling - after")
with result:
calling - before
calling - after
Use default logging and logback.xml for output configuration.
default clojure logging
I'm running into some issues with reporting on failures using the clojure.test testing framework.
Now, I understand that I can override some functions for different reporting so that it prints out to the console or wherever I want it to print to. I also understand that I can save this output to a file.
My issue is the following... when I declare a deftest like this example:
(deftest test1
(is (= 1 1)
(is (= 2 1))
This test will run and if I do something like (run-tests) or (test-var #'test1) it will return nil but print the failures.
I decided to override the :fail method for reporting, because what I want is a map of the failures like this: {"expected" (:expected m), "actual" (:actual m)} and this kinda sorta works if I were to just use the reporting function.
The problem is that when you run tests through the Clojure.test framework there are many macro's that get called and it doesn't behave it exactly how I want to.
My end goal is: running the tests, and if there are any failures, instead of printing them, save them to a map and return the map to me. If they all pass, then I don't care what it returns to me.
Is this even possible? I don't want to stop testing if a certain test fails, I just want it to be logged somewhere, preferably a map.
Sources:
Clojure test with mutiple assertions
https://clojure.github.io/clojure/branch-1.1.x/clojure.test-api.html
https://groups.google.com/forum/#!topic/clojure/vCjso96wqps
I'm afraid there's no easy way how to do that.
You could provide a custom implementation of clojure.test/report :fail defmethod and store the result in an atom but it's hard to propage the result to outer layers.
If you just use test-var then it's doable but note that test fixtures aren't executed in this case - see test-vars source:
(:use clojure.test)
(deftest failing
(testing "fail me"
(is (= 1 0))
(is (= 2 1))
(is (= 3 2))))
(def test-failures (atom []))
(defmethod report :fail [m]
(swap! test-failures
(fn [previous-failures current-failure]
(conj previous-failures current-failure))
{:test-var-str (testing-vars-str m)
:expected (:expected m)
:actual (:actual m)}))
(defmethod report :end-test-var [m]
#test-failures)
(defn run-test-var [v]
(reset! test-failures [])
(test-var v))
;; in REPL:
(run-test-var #'failing)
;; =>
[{:test-var-str "(failing) (form-init4939336553149581727.clj:159)", :expected 1, :actual (0)}
{:test-var-str "(failing) (form-init4939336553149581727.clj:160)", :expected 2, :actual (1)}
{:test-var-str "(failing) (form-init4939336553149581727.clj:161)", :expected 3, :actual (2)}]
There's also defmethod report :end-test-ns but this one is not very useful because test-ns function returns #*report-counters*.
I've almost implemented the well-known ring server, however the messages do not seem to be traversing the ring - here's my code:
module(ring).
-import(lists,[duplicate/2,append/1,zip/2,nthtail/2,nth/2,reverse/1]).
-export([start/3,server/0]).
start(M,N,Msg)->
start(M,N,[],Msg).
start(0,0,_,_)->
ok;
start(M,0,PList,Msg)->
nth(1,PList)!nthtail(1,reverse(zip(append(duplicate(M,PList)),duplicate(M*length(PList),Msg))));
start(M,N,PList,Msg)->
start(M,N-1,[spawn(ring, server, [])|PList],Msg).
server()->
receive
[]->
ok;
[{Pid,Msg}|T]->
io:format("~p,~p~n",[self(),Msg]),
Pid!T;
terminate->
true
end.
it returns the following when executed:
2> ring:start(3,3,"hello").
<0.42.0>,"hello"
<0.41.0>,"hello"
[{<0.41.0>,"hello"},
{<0.42.0>,"hello"},
{<0.40.0>,"hello"},
{<0.41.0>,"hello"},
{<0.42.0>,"hello"},
{<0.40.0>,"hello"},
{<0.41.0>,"hello"},
{<0.42.0>,"hello"}]
May I ask where I am going wrong here? I've checked the zipped process list, and it seems as if it should work. Thanks in advance.
There are 2 mistakes here, the main one is that you do not recursively recall server after printing the message.
The second one is that you should not remove the head of your list when you build the first message, otherwise you will have only m*n - 1 messages passed.
this code works, but it leaves all the processes active, you should enhance it to kill all processes at the end of the "ring":
-module(ring).
-import(lists,[duplicate/2,append/1,zip/2,nthtail/2,nth/2,reverse/1]).
-export([start/3,server/0]).
start(M,N,Msg)->
start(M,N,[],Msg).
start(0,0,_,_)->
ok;
start(M,0,PList,Msg)->
nth(1,PList)!reverse(zip(append(duplicate(M,PList)),duplicate(M*length(PList),Msg)));
start(M,N,PList,Msg)->
start(M,N-1,[spawn(ring, server, [])|PList],Msg).
server()->
receive
[]->
ok;
[{Pid,Msg}|T]->
io:format("In Server ~p,~p~n",[self(),Msg]),
Pid!T,
server();
terminate->
true
end.
On my side, I don't use import, I find it more explicit when I have lists:reverse..., You can use hd/1 to get the first element of a list, and you could use list comprehension to generate your list of {Pid,Msg}
Your processes are terminating, not looping (and there is never a condition under which they will receive 'terminate'). To solve the termination issue, have them spawn_link instead of just spawn so that when the first one dies, they all die.
It is good to kick things off by messaging yourself, to make sure you're not stripping the first message entirely.
-module(ring).
-import(lists,[duplicate/2,append/1,zip/2,nthtail/2,nth/2,reverse/1]).
-export([start/3,server/0]).
start(M, N, Msg)->
Scroll = start(M, N, [], Msg),
self() ! Scroll.
start(0, 0, _, _)->
ok;
start(M, 0, PList, Msg)->
nth(1, PList) ! nthtail(1, reverse(zip(append(duplicate(M, PList)),
duplicate(M * length(PList), Msg))));
start(M, N, PList, Msg)->
start(M, N - 1, [spawn_link(ring, server, []) | PList], Msg).
server()->
receive
[]->
ok;
[{Pid, Msg} | T]->
io:format("~p,~p~n", [self(), Msg]),
Pid ! T,
server()
end.
This produces:
1> c(ring).
{ok,ring}
2> ring:start(3,3,"raar!").
<0.42.0>,"raar!"
<0.41.0>,"raar!"
[{<0.41.0>,"raar!"},
{<0.42.0>,"raar!"},
{<0.40.0>,"raar!"},
{<0.41.0>,"raar!"},
{<0.42.0>,"raar!"},
{<0.40.0>,"raar!"},
{<0.41.0>,"raar!"},
{<0.42.0>,"raar!"}]
<0.42.0>,"raar!"
<0.40.0>,"raar!"
<0.41.0>,"raar!"
<0.42.0>,"raar!"
<0.40.0>,"raar!"
<0.41.0>,"raar!"
As expected. Note that I'm calling server() again on receipt of a message. When the empty list is received they all die because they are linked. No mess.
Some spacing for readability would have been a little more polite. Erlangers usually aren't so leet that we want to plow through a solid mass of characters -- and this actually causes errors with a few operators in some edge cases (like in map syntax). Also, using imported functions is a little less clear. I know is gums up the code with all that namespace business, but its a lifesaver when you start writing larger programs (there are a lot of list operations in the erlang module -- so some of this importing is unnecessary anyway http://www.erlang.org/doc/man/erlang.html#hd-1).
I have a small program that is supposed to read SQL queries/commands one by one and execute them against a database.
If a query executes successfully, the next query is executed.
If there is an error executing one query, the program should stop executing all together.
I have the code, except that the query still continues execution even when there is an exception.
(defn main
[]
(loop [queries (get-all-queries)
querycount 1]
(let [q (first queries)]
(println (format "currently processing query %s", querycount))
(cond (nil? q) (println "All Queries ran successfully.")
:else (do
(cond (= (:status (process-query q querycount)) "OK")
(recur (rest queries) (+querycount 1)))
:else (println "An error occured while running queries")))))))
(defn process-query
[query query-count]
(let [{query-body :query-body, is-query-running? :is-query-running?} query
my-agent (agent
{:error false, :query-count query-count}
:error-handler handler-fn)]
(send my-agent (fn[_]
(execute-query! db query-body)))))
(loop [is-query-running? (is-query-running?)
error? (:error #my-agent)]
(cond error? (do (println "Error")
{:status "ERROR" :error-msg (:error-msg #my-agent)})
(and (not is-query-running?) (not error?)) (do (println "Success")
{:status "OK"})
(:else (do
(Thread/sleep 2000)
(recur (is-query-running?) (:error #my-agent)))))))
(defn handler-fn
[agent exception]
(println (format "an exception occured : %s" exception))
(if (instance? java.sql.BatchUpdateException exception)
(println (.getNextException exception)))
(send agent (? [_] {:error true, :error-message exception}))
(throw exception))
The reason why I'm using an agent is that I have some queries that take 4 hours to run.
and when that happens, the database does not notify the program that the query has been completed. instead, the program is stuck. so, instead, I constantly poll to check if the query is done already.
Is this the best way to accomplish what I'm trying to do ?
Should I be using any other concurrency primitives ?
Do I even need concurrency primitives ?
I've been thinking about this for a long time now.
I think you will need to use core.async to resolve this kind of workflow
Take a look at http://clojure.com/blog/2013/06/28/clojure-core-async-channels.html
This lib will let you to check your conditions with the related asynchronous tasks involved
A few resources that may help you
http://www.infoq.com/news/2013/07/core-async
https://www.youtube.com/watch?v=AhxcGGeh5ho
The main problem seems to be: on the one hand, you write that the long queries never return, i.e. they don't even throw exceptions. On the other hand, your error detection mechanism for the agent is based on catching an exception.
I think what you need to do is not check (primarily) whether an exception was caught, but whether execute-query has actually returned a valid result when is-query-running? returns false.
Regarding the right concurrency primitive, I would suggest using a future instead of an agent. They are simpler than agents, since they can only return a single value, instead of changing their state multiple times, and their way of error handling is to simply return the exception instead of the regular return value.
You can then follow this implementation idea: in the loop, do a deref with timeout on the future. If the return value of the deref is whatever execute-query! returns regularly, return "OK"(resp. add a second expression to the future body as a clearly identifiable return value, e.g. the keyword :ok). Otherwise, if the return value of the deref is an exception, return "ERROR" with the :error-msg from the exception like you do now. Finally, if the return value is the timeout value you gave to the deref, call is-query-running?. If it's true, loop another time, if it's false, return ERROR with a special :error-msg which communicates that your query ended without either returning nor throwing an exception. (And probably call future-cancel so you don't leak threads of never-ending execute-query! calls.)
Whenever I create a large Mathematica project I run into this problem: Preventing avalanche of runtime errors in Mathematica, i.e., Mathematica's error message are opaque, archaic, and legion.
The idea then is to disable all of Mathematica's own error messages and implement type checking and error messages of your own in every Function and Module. However I have not found a simple and efficient way of doing this and end up with, e.g., some function generating an error 20 function calls deep and then get a whole cascade of error messages all the way back up to the main routine.
How would you set up a simple mechanism for this that only generates one error message at the function that experiences the error and a simple list of the chain of function calls?
EDIT: Since it has come up in a couple of answers; I am specifically looking for something lightweight regarding the output it produces (otherwise I could just stick with Mathematica's error messages) and obviously also lightweight in computational overhead. So while Stack and Trace are definitely light on the overhead, their output in complex projects is not quick to parse and some work needs to be done simplifying it.
YAsI - Yet Another (silly?) Idea ...
Re-reading your question ...
The idea then is to disable all of Mathematica's own error messages and implement type checking and error messages of your own in every Function and Module.
Found this:
$MessagePrePrint = ( #; Print[Stack[_][[;; -5]]]; Abort[]) &
v[x_, y_] := w[x, y];
w[x_, y_] := x/y;
StackComplete#v[1, 0];
During evaluation of In[267]:= {StackComplete[v[1,0]];,
StackComplete[v[1,0]], v[1,0], w[1,0], 1/0, 1/0, Message[Power::infy,1/0]}
Out[267]= $Aborted
conclusion ... Aborts at first message and leaves a "reasonable" stack trace. "Reasonable" means "Should be improved".
But it is completely non-intrusive!
To get the ball rolling here is one idea that I've been toying with; the creation of a pseudo stack.
First make a global variable theStack={} and then in every Function or Module start with AppendTo[theStack,"thisFuncName"] and end with theStack=Most#theStack. Assuming moderate (~a few tens) depth of function calls, this should not add any significant overhead.
Then implement your own typing/error checking and use Print#theStack;Abort[]; on errors.
Refinements of this method could include:
Figuring out a way to dynamically get "thisFuncionName" so that the AppendTo[] can be made into an identical function call for all Functions and Module.
Using Message[] Instead of Print[].
Pushing other important variables / stateful information on theStack.
One attempt to implement #Timo's idea (theStack)
Incomplete and perhaps flawed, but just to keep thinking about it:
Clear["Global`*"];
funcDef = t_[args___] \[CircleMinus] a_ :>
{t["nude", args] := a,
ReleaseHold[Hold[t[args] :=
(If[! ValueQ[theStack], theStack = {}];
AppendTo[theStack, ToString[t]];
Check[ss = a, Print[{"-TheStack->", Evaluate#theStack}];
Print#Hold[a]; Abort[]];
theStack = Most#theStack;
Return[ss])
]]};
v[x_, y_]\[CircleMinus] (Sin# g[x, y]) /. funcDef;
g[x_, y_]\[CircleMinus] x/y /. funcDef;
v[2, 3]
v[2, 0]
Output:
Out[299]= Sin[2/3]
During evaluation of In[295]:= Power::infy: Infinite expression 1/0 encountered. >>
During evaluation of In[295]:= {-TheStack->,{v,g}}
During evaluation of In[295]:= Hold[2/0]
Out[300]= $Aborted
A suggestion for extracting stack, maybe something that relies on Trace?
An example of using Trace below, from Chris Chiasson. This code saves evaluation tree of 1 + Sin[x + y] + Tan[x + y] into ~/temp/msgStream.m
Developer`ClearCache[];
SetAttributes[recordSteps, HoldAll];
recordSteps[expr_] :=
Block[{$Output = List#OpenWrite["~/temp/msgStream.m"]},
TracePrint[Unevaluated[expr], _?(FreeQ[#, Off] &),
TraceInternal -> True];
Close /# $Output;
Thread[
Union#Cases[
ReadList["~/temp/msgStream.m", HoldComplete[Expression]],
symb_Symbol /;
AtomQ#Unevaluated#symb &&
Context#Unevaluated#symb === "System`" :>
HoldComplete#symb, {0, Infinity}, Heads -> True],
HoldComplete]
];
recordSteps[1 + Tan[x + y] + Sin[x + y]]
To answer Samsdram's question, the code below (also from Chris) gives evaluation tree of a Mathematica expression. Here is the post from MathGroup with source code and examples.
(Attributes## = {HoldAllComplete}) & /# {traceToTreeAux, toVertex,
HoldFormComplete, getAtoms, getAtomsAux}
MakeBoxes[HoldFormComplete[args___], form_] :=
MakeBoxes[HoldForm[args], form]
edge[{head1_, pos1_, xpr1_}, {head2_, pos2_, xpr2_}] :=
Quiet[Rule[{head1, vertexNumberFunction#pos1, xpr1}, {head2,
vertexNumberFunction#pos2, xpr2}], {Rule::"rhs"}]
getAtomsAux[atom_ /; AtomQ#Unevaluated#atom] :=
Sow[HoldFormComplete#atom, getAtomsAux]
getAtomsAux[xpr_] := Map[getAtomsAux, Unevaluated#xpr, Heads -> True]
getAtoms[xpr_] := Flatten#Reap[getAtomsAux#xpr][[2]]
toVertex[traceToTreeAux[HoldForm[heldXpr_], pos_]] := toVertex[heldXpr]
toVertex[traceToTreeAux[HoldForm[heldXprs___], pos_]] :=
toVertex#traceToTreeAux[Sequence[], pos]
(*this code is strong enough to not need the ToString commands,but \
some of the resulting graph vertices give trouble to the graphing \
routines*)
toVertex[
traceToTreeAux[xpr_, pos_]] := {ToString[
Short#Extract[Unevaluated#xpr, 0, HoldFormComplete], StandardForm],
pos, ToString[Short#First#originalTraceExtract#{pos}, StandardForm]}
traceToTreeAux[xpr_ /; AtomQ#Unevaluated#xpr, ___] := Sequence[]
traceToTreeAux[_HoldForm, ___] := Sequence[]
traceToTreeAux[xpr_, pos_] :=
With[{lhs = toVertex#traceToTreeAux[xpr, pos],
args = HoldComplete ## Unevaluated#xpr},
Identity[Sequence][
ReleaseHold[
Function[Null, edge[lhs, toVertex##], HoldAllComplete] /# args],
ReleaseHold#args]]
traceToTree[xpr_] :=
Block[{vertexNumber = -1, vertexNumberFunction,
originalTraceExtract},
vertexNumberFunction[arg_] :=
vertexNumberFunction[arg] = ++vertexNumber;
originalTraceExtract[pos_] :=
Extract[Unevaluated#xpr, pos, HoldFormComplete]; {MapIndexed[
traceToTreeAux, Unevaluated#xpr, {0, Infinity}]}]
TraceTreeFormPlot[trace_, opts___] :=
Block[{$traceExpressionToTree = True},
Through#{Unprotect, Update}#SparseArray`ExpressionToTree;
SparseArray`ExpressionToTree[trace, Infinity] = traceToTree#trace;
With[{result = ToExpression#ToBoxes#TreeForm[trace, opts]},
Through#{Unprotect, Update}#SparseArray`ExpressionToTree;
SparseArray`ExpressionToTree[trace, Infinity] =.;
Through#{Update, Protect, Update}#SparseArray`ExpressionToTree;
result]];
TraceTreeFormPlot[Trace[Tan[x] + Sin[x] - 2*3 - 55]]
Perhaps we have been over thinking this. What if we just tweaked the pattern matching on the arguments a little. For instance, if we modified the function to check for a numeric quantity and added some code to print an error if it fails. For instance,
TypeNumeric[x_] := If[! NumericQ[Evaluate[x]],
Print["error at "]; Print[Stack[]]; Print["Expression "]; Print[x]; Print["Did
not return a numeric value"];Return[False],
(*Else*)
Return[True];]
SetAttributes[TypeNumeric, HoldAll];
Step 2: If you have a function, f[x_] that requires a numeric quantity, just write it with the standard pattern test and all should be well
Input:
f[x_?TypeNumeric] := Sqrt[x]
f[Log[y]]
f[Log[5]]
Output:
error at
{f}
Expression
Log[y]
Did not return a numeric value
f[Log[y]]
Sqrt[Log[5]]
I believe this will work and, it makes robust type checking as simple as a writing a function or two. The problem is that this could be hugely inefficient because this code evaluates the expression x twice, once for the type checking and once for real. This could be bad if an expensive function call is involved.
I haven't figured out the way around this second problem and would welcome suggestions on that front. Are continuations the way out of this problem?
Hope this helps.