:- module(handle_tests, []).

:- use_module(library(array)).
:- use_module(library(array/handle)).
:- use_module(library(array/buffer)).
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).
:- use_module('../examples/linalg', [blocked_cholesky/4, spd/2]).
:- use_module(library(clpBNR)).
:- op(20, yf, []).

:- begin_tests(handle).

matmul(A, B, C, N, M, P) :-
   shape(A, [N, M]), shape(B, [M, P]), shape(C, [N, P]),
   over([I:N, J:P], [C[I, J] := 0]),
   over([I:N, J:P, K:M], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]).

% tensor(+Type, +Shape, +Values, -Name): a name realized on host with Values.
tensor(Type, Shape, Values, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   compound_name_arguments(Data, data, Values),
   buffer_from_data(Buffer, Type, N, Data),
   shape(Name, Shape),
   type_kind(Type, Kind),
   kind(Name, Kind),
   value(Name, Buffer).

type_kind(float32, float).
type_kind(int32, int).

% domain_of(+Extent, -Domain): the clpBNR domain of a fresh copy of Extent, by its goals.
goals_of(Term, Goals) :-
   copy_term(Term, _, Goals).

% The slots come in the order of the program: the first matmul's inputs, then the second's
% right-hand side, whatever the order the variables were made in.
test(slot_order, [timeout(10)]) :-
   N::integer(1, 64),
   matmul(A, B, H, N, 4, 8),
   matmul(H, C, Y, N, 8, 2),
   signature(Y, Slots, OutSlot, _),
   Slots = [slot(S1, _, _, _), slot(S2, _, _, _), slot(S3, _, _, _)],
   S1 == A, S2 == B, S3 == C,
   OutSlot = slot(O, _, _, _),
   O == Y.

test(shapes_share_fresh_extents, [timeout(10)]) :-
   N::integer(1, 64),
   matmul(_, _, C, N, 4, 8),
   signature(C, [slot(_, SA, _, _), slot(_, SB, _, _)], slot(_, SC, _, _), _),
   SA = [N1, 4], SB = [4, 8], SC = [N2, 8],
   var(N1), N1 == N2, N1 \== N,
   \+ attvar(N1).

% A realized name is a slot like any input, whatever its boxes: weights, realized on the
% device, are arguments of the handle, in their place in the program.
test(realized_names_are_slots, [timeout(60)]) :-
   N::integer(1, 64),
   tensor(float32, [4, 8], [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
                            1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8], W),
   copy(W, Wd, pocl),
   realize([Wd], [], []),
   matmul(A, Wd, C, N, 4, 8),
   signature(C, Slots, _, _),
   Slots = [slot(S, _, _, _), slot(SW, [4, 8], float, pocl)],
   S == A, SW == Wd.

% args_of(+Out, +Bound, -Args): the arguments of the handle of Out in the order of its
% signature: the realized name Bound gives each slot's name, else the name itself, realized.
args_of(Out, Bound, Args) :-
   signature(Out, Slots, _, _),
   maplist(arg_of(Bound), Slots, Args).

arg_of(Bound, slot(Name, _, _, _), Arg), member(N1-Arg0, Bound), N1 == Name => Arg = Arg0.
arg_of(_, slot(Name, _, _, _), Arg) => Arg = Name.

% Executed on the fresh copy, the goals give the extents their domains again: a size in the
% domain unifies, one outside it does not.
test(goals_rebuild_domain, [timeout(10)]) :-
   B::integer(1, 1024),
   matmul(_, _, Y, B, 784, 10),
   signature(Y, [slot(_, SX, _, _), _], slot(_, SY, _, _), Goals),
   SX = [B1, 784], SY = [B2, 10],
   maplist(call, Goals),
   \+ B1 = 2000,
   \+ B1 = 0,
   B1 = 7,
   B2 == 7.

test(goals_keep_relations, [timeout(10)]) :-
   N::integer(0, 64), M::integer(0, 64), {N == 2*M},
   shape(X, [N, M]), shape(Y, [N, M]),
   over([I:N, J:M], [Y[I, J] := X[I, J]]),
   signature(Y, [slot(_, [N1, M1], _, _)], _, Goals),
   maplist(call, Goals),
   N1 = 6, M1 == 3.

test(goals_keep_power_of_two, [timeout(10)]) :-
   N::integer(1, 1024), power_of_two(N),
   shape(X, [N]), shape(Y, [N]),
   over([I:N], [Y[I] := X[I]]),
   signature(Y, [slot(_, [N1], _, _)], _, Goals),
   maplist(call, Goals),
   \+ N1 = 6,
   N1 = 8.

% A relation between two extents comes from each of them, and is kept once.
test(goals_once, [timeout(10)]) :-
   N::integer(0, 64), M::integer(0, 64), {N == 2*M},
   shape(X, [N, M]), shape(Y, [N, M]),
   over([I:N, J:M], [Y[I, J] := X[I, J]]),
   signature(Y, _, _, Goals),
   include([G]>>subsumes_term({_}, G), Goals, Relations),
   length(Relations, 1).

% The signature changes nothing: the extents keep their goals, the kinds stay open.
test(program_untouched, [timeout(10)]) :-
   N::integer(1, 64),
   matmul(A, B, C, N, 4, 8),
   goals_of(N, Before),
   signature(C, _, _, _),
   goals_of(N, After),
   Before =@= After,
   get_attr(A, kind, KA), \+ integer(KA),
   get_attr(B, kind, KB), \+ integer(KB).

test(kinds_resolved, [timeout(10)]) :-
   shape(I, [3]), kind(I, int), elements(I, 0-100), shape(X, [3]), shape(Y, [3]),
   over([J:3], [Y[J] := X[J] * I[J]]),
   signature(Y, [slot(_, _, KX, _), slot(_, _, KI, _)], slot(_, _, KY, _), _),
   KX == float, KI == int, KY == float.

test(devices, [timeout(10)]) :-
   N::integer(1, 64),
   matmul(A, _, C, N, 4, 8),
   copy(C, H, host),
   signature(H, [slot(_, _, _, DA), slot(_, _, _, DB)], slot(_, _, _, DH), _),
   var(DA), DA == DB, DH == host,
   device(A, D), D == DA.

test(unbounded_extent_is_no_error, [timeout(10)]) :-
   matmul(_, _, C, _, 4, 8),
   signature(C, [slot(_, [N1, 4], _, _), _], _, Goals),
   maplist(call, Goals),
   N1 = 100000.

% Handles
% =======

% read_back(+Name, -Values): the elements of a realized name, read back from its device.
read_back(Name, Values) :-
   run(Name, [], Values, []).

near(Xs, Ys) :-
   maplist([X, Y]>>(abs(X - Y) < 1.0e-4), Xs, Ys).

% chain(-Ah, -Bh, -Wd, -Yh, -N, ?D): Y = (A B) W on D, A and B from host, W realized on D, a
% slot after them, Y back on host, N the rows of A, in 1..8.
chain(Ah, Bh, Wd, Yh, N, D) :-
   N::integer(1, 8),
   shape(Ah, [N, 3]), device(Ah, host),
   shape(Bh, [3, 2]), device(Bh, host),
   copy(Ah, A, D), copy(Bh, B, D),
   matmul(A, B, H, N, 3, 2),
   tensor(float32, [2, 2], [1, 2, 3, 4], W),
   copy(W, Wd, D), realize([Wd], [], [device(D)]),
   matmul(H, Wd, Y, N, 2, 2),
   copy(Y, Yh, host).

% One handle serves every size of its program: compiled once, run on two batches of rows,
% the results those of eval/3, and the program's extent as symbolic as it was.
test(one_handle_every_size, [timeout(120), forall(test_device(D, _))]) :-
   chain(Ah, Bh, Wd, Yh, N, D),
   compile(Yh, [], Exe),
   signature(Exe, [slot([N1, 3], float, host), slot([3, 2], float, host), slot([2, 2], float, D)],
             slot([N2, 2], float, host)),
   N1 == N2, var(N1), N1 \== N,
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], A2),
   tensor(float32, [3, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9], A3),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B),
   run(Exe, [A2, B, Wd], R2), run(Exe, [A3, B, Wd], R3),
   shape(R2, [2, 2]), shape(R3, [3, 2]), device(R2, host), kind(R2, float),
   read_back(R2, V2), read_back(R3, V3),
   eval(Yh, [Ah-[1, 2, 3, 4, 5, 6], Bh-[1, 0, 0, 1, 1, 1]], E2),
   eval(Yh, [Ah-[1, 2, 3, 4, 5, 6, 7, 8, 9], Bh-[1, 0, 0, 1, 1, 1]], E3),
   near(V2, E2), near(V3, E3),
   var(N),
   release(Exe).

% A result on a device: the output of a program that ends there is realized there, an int's
% elements bounded by their value.
test(result_on_device, [timeout(120), forall(test_device(D, _))]) :-
   N::integer(1, 16),
   shape(Ih, [N]), kind(Ih, int), device(Ih, host),
   copy(Ih, I, D),
   shape(Y, [N]),
   over([J:N], [Y[J] := I[J] * 2 - 1]),
   compile(Y, [], Exe),
   signature(Exe, [slot([_], int, host)], slot([_], int, D)),
   tensor(int32, [3], [5, 1, 3], Arg),
   run(Exe, [Arg], R),
   device(R, D), kind(R, int), shape(R, [3]),
   read_back(R, [9, 1, 5]),
   elements(R, Range), Range == 1-9,
   release(Exe).

% A plan with a host loop: the blocked Cholesky's panels, a forall/2 of the clause.
test(host_loop, [timeout(300), forall(test_device(D, _))]) :-
   shape(Ah, [128, 128]), device(Ah, host),
   copy(Ah, A, D),
   blocked_cholesky(A, L, 128, 32),
   copy(L, Lh, host),
   compile(Lh, [], Exe),
   spd(128, As),
   tensor(float32, [128, 128], As, Arg),
   run(Exe, [Arg], R),
   read_back(R, Vs),
   eval(Lh, [Ah-As], Ref),
   near(Vs, Ref),
   release(Exe).

% The arguments are checked against the slots: their number, where they live, their kind,
% and their shape within the domain of the extents.
test(arguments_checked, [timeout(120)]) :-
   chain(_, _, Wd, Yh, _, pocl),
   compile(Yh, [], Exe),
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], A),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B),
   catch(run(Exe, [A, B], _), error(domain_error(arguments(3), _), _), true),
   tensor(int32, [2, 3], [1, 2, 3, 4, 5, 6], Ai),
   catch(run(Exe, [Ai, B, Wd], _), error(domain_error(kind(float), _), _), true),
   copy(A, Ad, pocl), realize([Ad], [], []),
   catch(run(Exe, [Ad, B, Wd], _), error(domain_error(device(host), _), _), true),
   tensor(float32, [2, 2], [1, 2, 3, 4], Bad),
   catch(run(Exe, [A, Bad, Wd], _), error(domain_error(shape([3, 2]), _), _), true),
   numlist(1, 27, Vs), tensor(float32, [9, 3], Vs, Big),
   catch(run(Exe, [Big, B, Wd], _), error(domain_error(shape(_), _), _), true),
   shape(U, [2]),
   catch(run(Exe, [U, B, Wd], _), error(type_error(realized_name, _), _), true),
   catch(run(Exe, [A, B, Bad], _), error(domain_error(device(pocl), _), _), true),
   copy(B, Bd, pocl), realize([Bd], [], []),
   catch(run(Exe, [A, B, Bd], _), error(domain_error(shape([2, 2]), _), _), true),
   release(Exe).

test(released_handle, [timeout(60), error(existence_error(handle, _))]) :-
   chain(_, _, Wd, Yh, _, pocl),
   compile(Yh, [], Exe),
   release(Exe),
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], A),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B),
   run(Exe, [A, B, Wd], _).

test(unbounded_extent_has_no_handle, [timeout(60), error(domain_error(bounded_extent, _))]) :-
   shape(Ah, [N, 3]), device(Ah, host), shape(Bh, [3, 2]), device(Bh, host),
   copy(Ah, A, pocl), copy(Bh, B, pocl),
   matmul(A, B, C, N, 3, 2),
   copy(C, Ch, host),
   compile(Ch, [], _).

% Calls are independent: four threads run one handle at once, each on its own size.
% Calls are independent: four threads run one handle at once, each on its own size. A name
% does not cross threads: each thread's goal carries the weights' cl_mem and makes a name of
% it, realized with the same elements.
test(concurrent_calls, [timeout(120)]) :-
   chain(Ah, Bh, Wd, Yh, _, pocl),
   compile(Yh, [], Exe),
   value(Wd, Mem),
   findall(K-Vs, ( between(1, 4, K), L is K*3, numlist(1, L, Vs) ), Batches),
   maplist(reference(Yh, Ah, Bh), Batches, Refs),
   concurrent_maplist(call_on(Exe, Mem), Batches, Outs),
   maplist(near, Outs, Refs),
   release(Exe).

reference(Yh, Ah, Bh, _-Vs, Ref) :-
   eval(Yh, [Ah-Vs, Bh-[1, 0, 0, 1, 1, 1]], Ref).

call_on(Exe, Mem, K-Vs, Out) :-
   tensor(float32, [K, 3], Vs, A),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B),
   shape(W, [2, 2]), kind(W, float),
   core:realize_value(W, Mem, pocl, none),
   run(Exe, [A, B, W], R),
   read_back(R, Out).

% Data as realized names, and the cache
% =====================================

% A realized name given as the data of an input: on the input's device it is the argument
% itself, from host it is uploaded; the result as a name stays where Out is.
test(realized_data, [timeout(120), forall(test_device(D, _))]) :-
   matmul(A, B, C, 2, 3, 2),
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], Ah),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], Bh),
   copy(Bh, Bd, D), realize([Bd], [], []),
   run(C, [A-Ah, B-Bd], R, [device(D), result(name)]),
   core:realized(R), device(R, D), shape(R, [2, 2]),
   read_back(R, Vs),
   eval(C, [A-Ah, B-Bd], Ref),
   near(Vs, Ref), Ref = [4.0, 5.0, 10.0, 11.0],
   run(C, [A-Ah, B-Bd], Vs1, [device(D)]),
   near(Vs1, Ref).

test(data_must_be_realized, [timeout(60), error(type_error(realized_name, _))]) :-
   matmul(A, B, C, 2, 3, 2),
   shape(U, [2, 3]),
   run(C, [A-U, B-[1, 0, 0, 1, 1, 1]], _, []).

% The range a slot's name declares holds the argument's elements: data outside it through
% run/4, or a realized name outside it through run/3, is a domain error before anything runs,
% and a range in an extent is at the size of the call.
gather(Td, Idx, Y, N) :-
   shape(Idx, [N]), elements(Idx, 0-3),
   over([I:N], [Y[I] := Td[Idx[I]]]).

constant(Td) :-
   tensor(float32, [4], [5, 6, 7, 8], T),
   copy(T, Td, pocl), realize([Td], [], []).

test(data_outside_the_range, [timeout(120), error(domain_error(elements(0-3), _))]) :-
   constant(Td), gather(Td, Idx, Y, 4),
   run(Y, [Idx-[0, 1, 2, 700]], _, []).

test(data_at_the_edges_of_the_range, [timeout(120), true(V == [8.0, 5.0, 8.0, 5.0])]) :-
   constant(Td), gather(Td, Idx, Y, 4),
   run(Y, [Idx-[3, 0, 3, 0]], V, []).

test(argument_outside_the_range, [timeout(120), error(domain_error(elements(0-3), _))]) :-
   constant(Td), gather(Td, Idx, Y, 4),
   compile(Y, [], Exe),
   tensor(int32, [4], [0, 1, 2, 4], Ih),
   copy(Ih, Id, pocl), realize([Id], [], []),
   args_of(Y, [Idx-Id], Args),
   run(Exe, Args, _).

% The slot of a realized index without a range has the bounds of its value, which the
% program's subscripts were checked against: another index is held to them.
test(realized_index_bounds_its_slot, [timeout(120)]) :-
   tensor(int32, [3], [2, 0, 1], Ih),
   copy(Ih, Idx, pocl), realize([Idx], [], []),
   shape(X, [3]), shape(Y, [3]),
   over([I:3], [Y[I] := X[Idx[I]]]),
   signature(Y, Slots, _, _),
   handle:slot_range(Idx, Range), Range == 0-2,
   compile(Y, [], Exe),
   tensor(float32, [3], [5, 6, 7], Xh),
   copy(Xh, Xd, pocl), realize([Xd], [], []),
   args_of(Y, [X-Xd], Args),
   run(Exe, Args, R), read_back(R, [7.0, 5.0, 6.0]),
   tensor(int32, [3], [1, 1, 0], Jh),
   copy(Jh, Jd, pocl), realize([Jd], [], []),
   args_of(Y, [X-Xd, Idx-Jd], Args1),
   run(Exe, Args1, R1), read_back(R1, [6.0, 6.0, 5.0]),
   tensor(int32, [3], [1, 3, 0], Kh),
   copy(Kh, Kd, pocl), realize([Kd], [], []),
   args_of(Y, [X-Xd, Idx-Kd], Args2),
   catch(run(Exe, Args2, _), error(domain_error(elements(0-2), _), _), true),
   length(Slots, 2),
   release(Exe).

test(range_in_an_extent_at_the_size_of_the_call, [timeout(120), error(domain_error(elements(0-2), _))]) :-
   N::integer(1, 8),
   shape(X, [N]), shape(Idx, [N]), elements(Idx, 0-(N-1)),
   over([I:N], [Y[I] := X[Idx[I]]]),
   run(Y, [X-[1, 2, 3], Idx-[2, 1, 0]], V, []), V == [3.0, 2.0, 1.0],
   run(Y, [X-[1, 2, 3], Idx-[2, 3, 0]], _, []).

% A program run again, rebuilt as a variant of one run before, runs the handle of the first,
% laid out at the first run's sizes, at any size after.
test(cache_reuses_a_handle, [timeout(120)]) :-
   flush_handles,
   matmul(A1, B1, C1, N1, 3, 2),
   numlist(1, 6, As1), run(C1, [A1-As1, B1-[1, 0, 0, 1, 1, 1]], V1, []),
   cached(1),
   matmul(A2, B2, C2, N2, 3, 2),
   numlist(1, 30, As2), run(C2, [A2-As2, B2-[1, 0, 0, 1, 1, 1]], V2, []),
   cached(1),
   eval(C1, [A1-As1, B1-[1, 0, 0, 1, 1, 1]], R1), near(V1, R1),
   eval(C2, [A2-As2, B2-[1, 0, 0, 1, 1, 1]], R2), near(V2, R2),
   var(N1), var(N2),
   matmul(A3, B3, C3, _, 4, 2),
   numlist(1, 8, As3), run(C3, [A3-As3, B3-[1, 0, 0, 1, 1, 1, 0, 0]], _, []),
   cached(2),
   flush_handles,
   cached(0),
   run(C3, [A3-As3, B3-[1, 0, 0, 1, 1, 1, 0, 0]], V3, []),
   eval(C3, [A3-As3, B3-[1, 0, 0, 1, 1, 1, 0, 0]], R3), near(V3, R3).

cached(N) :-
   aggregate_all(count, handle:cache(_, _, _, _), N).

% The key is the program's structure, never a buffer: the same program over other weights
% realized is the same handle, run on them as its argument, and a realized name given as
% the data of another is its argument too. The realize/3 of a copy is a run too, cached
% like any.
test(cache_keys_structure_not_buffers, [timeout(120)]) :-
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], W1),
   copy(W1, Wd1, pocl), realize([Wd1], [], []),
   tensor(float32, [3, 2], [2, 0, 0, 2, 2, 2], W2),
   copy(W2, Wd2, pocl), realize([Wd2], [], []),
   flush_handles,
   matmul(A1, Wd1, C1, 2, 3, 2), run(C1, [A1-[1, 2, 3, 4, 5, 6]], V1, []),
   matmul(A2, Wd1, C2, 2, 3, 2), run(C2, [A2-[1, 2, 3, 4, 5, 6]], V1, []),
   cached(1),
   matmul(A3, Wd2, C3, 2, 3, 2), run(C3, [A3-[1, 2, 3, 4, 5, 6]], V3, []),
   cached(1),
   maplist([X, Y]>>(Y =:= 2*X), V1, V3),
   run(C1, [A1-[1, 2, 3, 4, 5, 6], Wd1-Wd2], V4, []),
   V4 == V3,
   cached(1),
   handle:cache(_, Key, _, _),
   \+ ( sub_term(T, Key), blob(T, cl_mem) ),
   flush_handles.

% The key is made at every run, by copies of the program alone: ground, the names their
% numbers, the same for the program again and for a variant of it built anew, another once
% a box is added, an extent bounded otherwise, or a shape a product of another number.
test(key_is_of_the_program, [timeout(60)]) :-
   N::integer(1, 64), matmul(_, _, C, N, 3, 2),
   key_of(C, K1), ground(K1),
   key_of(C, K2), K2 == K1,
   term_attvars(C, Vs), \+ ( member(V, Vs), get_attr(V, handle_key, _) ),
   K1 = key(_, [decl(Shape, _, _, _, _, _) | _]-Boxes, Goals),
   Shape = [E, 2], E = '$VAR'(_),
   Goals = [E::integer(1, 64)],
   once(( sub_term(Place, Boxes), Place = []([_, _], '$name'(1)) )),
   N2::integer(1, 64), matmul(_, _, C2, N2, 3, 2),
   key_of(C2, K3), K3 == K1,
   N3::integer(1, 32), matmul(_, _, C3, N3, 3, 2),
   key_of(C3, K4), K4 \== K1,
   over([I:N, J:2], [C[I, J] := C[I, J] + 1]),
   key_of(C, K5), K5 \== K1.
test(key_holds_a_product_extent, [timeout(60)]) :-
   K::integer(1, 8),
   shape(X, [4*K]), over([I:4*K], [Y[I] := X[I] + 1]),
   key_of(Y, K1),
   L::integer(1, 8),
   shape(X2, [4*L]), over([I2:4*L], [Y2[I2] := X2[I2] + 1]),
   key_of(Y2, K2), K2 == K1,
   M::integer(1, 8),
   shape(X3, [8*M]), over([I3:8*M], [Y3[I3] := X3[I3] + 1]),
   key_of(Y3, K3), K3 \== K1.

key_of(Out, Key) :-
   program(Out, Boxes),
   handle:compile_names(Boxes, Out, Names),
   handle:program_key(Boxes, Names, [], [], Key).

% The cache holds the last programs: over the flag, the oldest handle goes.
test(cache_is_bounded, [timeout(120), setup(set_prolog_flag(array_handle_cache, 2)),
                        cleanup(set_prolog_flag(array_handle_cache, 64))]) :-
   flush_handles,
   forall(member(M, [2, 3, 4]),
          ( matmul(A, B, C, 2, M, 2), L is 2*M, numlist(1, L, As), length(Bs, L), maplist(=(1), Bs),
            run(C, [A-As, B-Bs], _, []) )),
   cached(2),
   flush_handles.

% The handle on the name
% ======================

% A run keeps its handle on the name: the next run of the same name goes to the clause, and
% a box added since compiles again.
test(handle_on_the_name, [timeout(120)]) :-
   flush_handles,
   shape(X, [N]), device(X, host), copy(X, Xd, pocl),
   shape(Y, [N]), over([I:N], [Y[I] := Xd[I] * 2]),
   copy(Y, Yh, host),
   run(Yh, [X-[1, 2, 3]], V1, []), V1 == [2.0, 4.0, 6.0],
   get_attr(Yh, handle, bound(Exe, _)),
   run(Yh, [X-[1, 2, 3, 4]], V2, []), V2 == [2.0, 4.0, 6.0, 8.0],
   get_attr(Yh, handle, bound(Exe1, _)), Exe1 == Exe,
   over([I:N], [Y[I] := Y[I] + 1]),
   run(Yh, [X-[1, 2, 3]], V3, []), V3 == [3.0, 5.0, 7.0],
   get_attr(Yh, handle, bound(Exe2, _)), Exe2 \== Exe,
   flush_handles,
   run(Yh, [X-[1, 2]], V4, []), V4 == [3.0, 5.0],
   var(N).

% The handle on the name is of the program as its key holds it: a realized name realized
% again with another buffer, or unrealized into an input given data, is the same program,
% the slot the same, and the clause runs on the new value; a kind declared since is another
% program, and the next run compiles again rather than running the clause of the old one.
test(handle_stays_when_a_name_is_realized_again, [timeout(120)]) :-
   tensor(float32, [3], [1, 2, 3], W),
   copy(W, Wd, pocl),
   over([I:3], [Y[I] := Wd[I] * 10]),
   run(Y, [], V1, []), V1 == [10.0, 20.0, 30.0],
   get_attr(Y, handle, bound(Exe, _)),
   unrealize(W),
   buffer_from_data(Buffer, float32, 3, data(7.0, 8.0, 9.0)),
   value(W, Buffer),
   run(Y, [], V2, []), V2 == [70.0, 80.0, 90.0],
   get_attr(Y, handle, bound(Exe1, _)), Exe1 == Exe.

test(handle_follows_a_name_unrealized, [timeout(120)]) :-
   tensor(float32, [3], [1, 2, 3], W),
   copy(W, Wd, pocl),
   over([I:3], [Y[I] := Wd[I] * 10]),
   run(Y, [], V1, []), V1 == [10.0, 20.0, 30.0],
   get_attr(Y, handle, bound(Exe, _)),
   unrealize(W),
   run(Y, [W-[7, 8, 9]], V2, []), V2 == [70.0, 80.0, 90.0],
   get_attr(Y, handle, bound(Exe1, _)), Exe1 == Exe.

% A written name realized is an input too: its boxes are not run, and data given for it is
% its argument, not the start of its chain.
test(data_for_a_realized_written_name, [timeout(120)]) :-
   shape(X, [3]), shape(H, [3]), shape(Y, [3]),
   over([I:3], [H[I] := X[I] * 2]),
   over([I:3], [Y[I] := H[I] + 1]),
   realize([H], [X-[1, 2, 3]], [device(pocl)]),
   run(Y, [], V1, []), V1 == [3.0, 5.0, 7.0],
   run(Y, [H-[10, 20, 30]], V2, []), V2 == [11.0, 21.0, 31.0],
   tensor(float32, [3], [5, 6, 7], Hh),
   run(Y, [H-Hh], V3, []), V3 == [6.0, 7.0, 8.0],
   run(Y, [], V4, []), V4 == V1.

test(handle_follows_a_kind_declared, [timeout(120)]) :-
   shape(X, [2]),
   over([I:2], [Y[I] := X[I] * X[I]]),
   run(Y, [X-[1.5, 2.5]], V1, []), V1 == [2.25, 6.25],
   kind(X, int),
   run(Y, [X-[1.5, 2.5]], V2, []), V2 == [1, 4].

% compile/2 keeps the handle on the name without a run, and a tabled builder that ends with
% it hands every copy of its answer the handle: the copies run without the compiler, and
% program/2 knows a box across the names it writes in a copy that shares nothing.
:- table two_outputs/4.
two_outputs(D, A, B, C) :-
   shape(A, [2]), device(A, D), shape(B, [2]), shape(C, [2]),
   over([I:2], [B[I] := A[I] + 1, C[I] := B[I] * A[I]]),
   compile(C, [device(D)]).

test(tabled_builder, [timeout(120), forall(test_device(D, _))]) :-
   abolish_all_tables,
   two_outputs(D, A1, _, C1),
   get_attr(C1, handle, bound(Exe, _)),
   two_outputs(D, A2, _, C2),
   A2 \== A1, C2 \== C1,
   get_attr(C2, handle, bound(Exe2, _)), Exe2 == Exe,
   tensor(float32, [2], [3, 4], Ah),
   copy(Ah, Ad, D), realize([Ad], [], []),
   run(C2, [A2-Ad], V, []), V == [12.0, 20.0],
   eval(C2, [A2-Ad], V),
   program(C2, Boxes), length(Boxes, 1).

% A box added twice is two boxes of the program, equal as they are.
test(twice_the_same_box, [timeout(60)]) :-
   shape(X, [2]), shape(Y, [2]),
   over([I:2], [Y[I] := 0]),
   over([I:2], [Y[I] := Y[I] + X[I]]),
   over([I:2], [Y[I] := Y[I] + X[I]]),
   program(Y, Boxes), length(Boxes, 3),
   eval(Y, [X-[1, 2]], [2.0, 4.0]),
   run(Y, [X-[1, 2]], [2.0, 4.0], []).

% The arena is kept
% =================

% A handle keeps its arena from one call to the next: the same buffer serves a call of the
% same size, a larger call gets a larger one, and release/1 drops it.
test(arena_kept, [timeout(120)]) :-
   chain(_, _, Wd, Yh, _, pocl),
   compile(Yh, [], Exe), Exe = exe(Id, _, _, _),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B),
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], A2),
   run(Exe, [A2, B, Wd], _),
   handle:arena_of(Id, pocl, Mem, Bytes),
   run(Exe, [A2, B, Wd], _),
   handle:arena_of(Id, pocl, Mem1, Bytes1), Mem1 == Mem, Bytes1 =:= Bytes,
   numlist(1, 24, Vs), tensor(float32, [8, 3], Vs, A8),
   run(Exe, [A8, B, Wd], R8),
   handle:arena_of(Id, pocl, Mem8, Bytes8), Bytes8 >= Bytes,
   (  Bytes8 > Bytes
   -> Mem8 \== Mem                       % grown
   ;  Mem8 == Mem                        % the alignment rounded both sizes to the same
   ),
   run(Exe, [A2, B, Wd], _),
   handle:arena_of(Id, pocl, Mem2, _), Mem2 == Mem8,
   read_back(R8, V8), length(V8, 16),
   release(Exe),
   \+ handle:arena_of(Id, _, _, _).

% A handle keeps its kernels too, one per entry it launches, made at the first call of the
% thread and set again at every launch, and release/1 drops them.
test(kernels_kept, [timeout(120)]) :-
   chain(_, _, Wd, Yh, _, pocl),
   compile(Yh, [], Exe), Exe = exe(Id, _, _, _),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B),
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], A2),
   \+ handle:kernels_of(Id, _, _),
   run(Exe, [A2, B, Wd], R1), read_back(R1, V1),
   handle:kernels_of(Id, pocl, Ks), Ks = [_ | _],
   numlist(1, 24, Vs), tensor(float32, [8, 3], Vs, A8),
   run(Exe, [A8, B, Wd], R8), read_back(R8, V8), length(V8, 16),
   run(Exe, [A2, B, Wd], R2), read_back(R2, V2), V2 == V1,
   handle:kernels_of(Id, pocl, Ks1), Ks1 == Ks,
   thread_create(( run(Exe, [A2, B, Wd], _), handle:kernels_of(Id, pocl, Kt), Kt \== Ks ), Thread),
   thread_join(Thread, Status), Status == true,
   release(Exe),
   \+ handle:kernels_of(Id, _, _).

% The state of a program
% ======================

% A run keeps the state of its program with the handle: a later run of the name, or of a
% copy of it, knows its boxes and its handle by the state, the program not walked; a box
% added since is another state, which the walk and the key decide.
test(state_knows_a_program_run_before, [timeout(120)]) :-
   flush_handles,
   shape(X, [N]), device(X, host), copy(X, Xd, pocl),
   shape(Y, [N]), over([I:N], [Y[I] := Xd[I] * 2]),
   copy(Y, Yh, host),
   handle:state([Yh], [], [], S0),
   \+ handle:known_state(S0, _, _, _),
   run(Yh, [X-[1, 2, 3]], V1, []), V1 == [2.0, 4.0, 6.0],
   get_attr(Yh, handle, bound(Exe, _)), Exe = exe(Id, _, _, _),
   handle:state([Yh], [], [], S1),
   handle:known_state(S1, Boxes1, Names1, Exe1), same_handle(Exe1, Exe),
   program(Yh, Walked1), Boxes1 == Walked1,
   handle:compile_names(Walked1, Yh, Named1), Names1 == Named1,
   copy_term(Yh-X, Yh2-X2),
   handle:state([Yh2], [], [], S2),
   handle:known_state(S2, Boxes2, _, Exe2), same_handle(Exe2, Exe),
   program(Yh2, Walked2), Boxes2 == Walked2, Boxes2 \== Boxes1,
   run(Yh2, [X2-[5]], V2, []), V2 == [10.0],
   over([I:N], [Y[I] := Y[I] + 1]),
   handle:state([Yh], [], [], S3),
   \+ handle:known_state(S3, _, _, _),
   run(Yh, [X-[1, 2, 3]], V3, []), V3 == [3.0, 5.0, 7.0],
   get_attr(Yh, handle, bound(Exe3, _)), \+ same_handle(Exe3, Exe),
   handle:state([Yh], [], [], S4),
   handle:known_state(S4, _, _, Exe4), same_handle(Exe4, Exe3),
   run(Yh2, [X2-[5, 6]], V4, []), V4 == [10.0, 12.0],
   Exe3 = exe(Id3, _, _, _),
   handle:known(_, Id3, _, _, _),
   flush_handles,
   \+ handle:known(_, Id, _, _, _),
   \+ handle:known(_, Id3, _, _, _),
   run(Yh2, [X2-[7]], V5, []), V5 == [14.0],
   var(N).

% same_handle(+Exe1, +Exe2): one handle, its slots over other variables or not.
same_handle(exe(Id1, Ref1, _, _), exe(Id2, Ref2, _, _)) :-
   Id1-Ref1 == Id2-Ref2.

% The state is of the run: its initial data and the options of its key are part of it, and
% a name realized again with another buffer has another state and the same handle.
test(state_is_of_the_run, [timeout(120)]) :-
   tensor(float32, [3], [1, 2, 3], W),
   copy(W, Wd, pocl),
   over([I:3], [Y[I] := Wd[I] * 10]),
   run(Y, [], V1, []), V1 == [10.0, 20.0, 30.0],
   get_attr(Y, handle, bound(Exe, _)),
   handle:state([Y], [], [], S1),
   handle:known_state(S1, _, _, Exe1), same_handle(Exe1, Exe),
   handle:state([Y], [], [outputs(1)], S2),
   \+ handle:known_state(S2, _, _, _),
   handle:state([Y], [], [device(_)], S3), S3 == none,
   unrealize(W),
   buffer_from_data(Buffer, float32, 3, data(7.0, 8.0, 9.0)),
   value(W, Buffer),
   handle:state([Y], [], [], S4),
   \+ handle:known_state(S4, _, _, _),
   run(Y, [], V2, []), V2 == [70.0, 80.0, 90.0],
   get_attr(Y, handle, bound(Exe5, _)), same_handle(Exe5, Exe),
   handle:state([Y], [], [], S5),
   handle:known_state(S5, _, _, Exe6), same_handle(Exe6, Exe).

% A box reads what a box before it wrote: an element no box wrote is an error of eval/3, and
% a program does not rely on zeroes.
test(unwritten_read, [timeout(60), error(existence_error(written_element, 1))]) :-
   shape(Y, [2]),
   over([I:2], [Y[I] := Y[I] + 1]),
   eval(Y, [], _).

% Several outputs in one handle: the product H, read by the second product, and Y, on a
% device or back on host, each a result; H is computed once, the plan of the two having
% the kernels of Y alone.
test(several_outputs, [timeout(120), forall(test_device(D, _))]) :-
   N::integer(1, 8),
   shape(Ah, [N, 3]), device(Ah, host),
   shape(Bh, [3, 2]), device(Bh, host),
   copy(Ah, A, D), copy(Bh, B, D),
   matmul(A, B, H, N, 3, 2),
   shape(Y, [N, 2]),
   over([I:N, J:2], [Y[I, J] := H[I, J] * 2 + 1]),
   copy(Y, Yh, host),
   compile_all([H, Yh], [], Exe),
   signature(Exe, [slot([N1, 3], float, host), slot([3, 2], float, host)],
             [slot([N2, 2], float, D), slot([N3, 2], float, host)]),
   N1 == N2, N2 == N3,
   tensor(float32, [2, 3], [1, 2, 3, 4, 5, 6], A2),
   tensor(float32, [3, 2], [1, 0, 0, 1, 1, 1], B2),
   run(Exe, [A2, B2], [Rh, Ry]),
   device(Rh, D), device(Ry, host), shape(Rh, [2, 2]),
   read_back(Rh, Vh), read_back(Ry, Vy),
   near(Vh, [4.0, 5.0, 10.0, 11.0]), near(Vy, [9.0, 11.0, 21.0, 23.0]),
   var(N),
   release(Exe).

% A pure name that is an output is computed, and still fused into the output that reads it.
test(outputs_are_not_fused_away, [timeout(120), true(V1-V2 == [2.0, 4.0]-[3.0, 5.0])]) :-
   shape(Xh, [2]), device(Xh, host),
   copy(Xh, X, pocl),
   over([I:2], [A[I] := X[I] * 2]),
   over([I:2], [B[I] := A[I] + 1]),
   compile_all([A, B], [], Exe),
   tensor(float32, [2], [1, 2], Arg),
   run(Exe, [Arg], [Ra, Rb]),
   read_back(Ra, V1), read_back(Rb, V2),
   release(Exe).

% Several outputs without a handle in sight: run_all/4 compiles at the first run and calls
% after, its results names given back as the data of the next run.
test(run_all_feeds_its_results_back, [timeout(120), forall(test_device(D, _))]) :-
   shape(Wh, [2]), device(Wh, host),
   copy(Wh, W, D),
   over([I:2], [A[I] := W[I] * 2]),
   over([], [S := 0]),
   over([I:2], [S := S + A[I]]),
   copy(A, Ah, host),
   tensor(float32, [2], [1, 2], W0),
   run_all([S, Ah], [Wh-W0], [S1, W1], []),
   run_all([S, Ah], [Wh-W1], [S2, W2], []),
   read_back(S1, [6.0]), read_back(S2, [12.0]), read_back(W2, [4.0, 8.0]),
   device(S1, D), device(W2, host),
   get_attr(S, handle, _).

:- end_tests(handle).
