 $$
 DECLARE
   times_token uuid;
-BEGIN
+--  ts timestamptz;
+BEGIN
+--  ts := clock_timestamp();
+
   CASE array_length(tokens,1)
     WHEN 0 THEN
       times_token:=gate_one();

  attribute RECORD;
BEGIN
  LOCK TABLE provenance_circuit_gate;
  INSERT INTO provenance_circuit_gate VALUES (NEW.provsql, 'input');
  RETURN NEW;
END
$$ LANGUAGE plpgsql SET search_path=provsql,pg_temp SECURITY DEFINER;


$$ LANGUAGE plpgsql SET search_path=provsql,pg_temp,public SECURITY DEFINER; 

CREATE OR REPLACE FUNCTION provenance_plus
  (state uuid[], token provenance_token)
  RETURNS uuid[] AS
$$
DECLARE
  plus_token uuid;
--  ts timestamptz;
BEGIN
--  ts := clock_timestamp();

  IF token = gate_zero() THEN
    return state;
  END IF;

--  raise notice 'plus time spent=%', clock_timestamp() - ts;

  RETURN array_append(state, token::uuid);
END
$$ LANGUAGE plpgsql SET search_path=provsql,pg_temp,public SECURITY DEFINER;

CREATE OR REPLACE FUNCTION provenance_plus_final(state uuid[])
  RETURNS provenance_token AS
$$
DECLARE
  c INTEGER;
  plus_token uuid;
  ts timestamptz;
BEGIN
--  ts := clock_timestamp();
  LOCK TABLE provenance_circuit_gate;
  c:=array_length(state, 1);

  IF c = 0 THEN
    plus_token := gate_zero();
  ELSIF c = 1 THEN
    plus_token := state[1];
  ELSE
    plus_token := uuid_generate_v5(
      uuid_ns_provsql(),
      concat('plus',array_to_string(state, ',')));

    BEGIN
      INSERT INTO provenance_circuit_gate VALUES(plus_token,'plus');
      INSERT INTO provenance_circuit_wire SELECT plus_token, * FROM unnest(state);
    EXCEPTION WHEN unique_violation THEN
    END;
  END IF;

--  raise notice 'plus_make_deterministic time spent=%', clock_timestamp() - ts;
  RETURN plus_token;
END
$$ LANGUAGE plpgsql STRICT SET search_path=provsql,pg_temp,public SECURITY DEFINER;

CREATE AGGREGATE provenance_agg(token provenance_token) (
  SFUNC = provenance_plus,
  STYPE = uuid[],
  INITCOND = '{}',
  FINALFUNC = provenance_plus_final
);

CREATE OR REPLACE FUNCTION trim_circuit()
