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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
%%%-------------------------------------------------------------------
|
| 2 |
+
%%% @doc HK-SEARCH :: one search job's pipeline execution.
|
| 3 |
+
%%%
|
| 4 |
+
%%% Implements the `<search_pipeline>' stage list as literal
|
| 5 |
+
%%% `gen_statem' states -- `user_query' through `frontend_visibility'
|
| 6 |
+
%%% plus terminal `done'/`failed' -- so the job's current state
|
| 7 |
+
%%% *is* its current pipeline stage, not a separate field that could
|
| 8 |
+
%%% drift from it. Every stage transition emits an `hk_event' before
|
| 9 |
+
%%% moving on, matching the example event names in the spec
|
| 10 |
+
%%% (`search.started', `search.query_generated', ... ,
|
| 11 |
+
%%% `search.completed'), plus a few unlisted-but-analogous ones for
|
| 12 |
+
%%% stages the spec didn't give an example event for
|
| 13 |
+
%%% (`search.query_normalized', `search.urls_deduplicated',
|
| 14 |
+
%%% `search.result_synthesized').
|
| 15 |
+
%%%
|
| 16 |
+
%%% `source_ranking' can loop back to `search_planner' (bumping
|
| 17 |
+
%%% `iteration') when too few ranked results were found, bounded by
|
| 18 |
+
%%% `max_iterations' -- the concrete enforcement point for the
|
| 19 |
+
%%% "maximum search iterations" limit from `<browser_agent_loop>'.
|
| 20 |
+
%%% @end
|
| 21 |
+
%%%-------------------------------------------------------------------
|
| 22 |
+
-module(hk_search_job).
|
| 23 |
+
-behaviour(gen_statem).
|
| 24 |
+
|
| 25 |
+
-include("hyperkitty.hrl").
|
| 26 |
+
|
| 27 |
+
-export([start_link/1, run/1, await_result/2, describe/1]).
|
| 28 |
+
-export([callback_mode/0, init/1]).
|
| 29 |
+
-export([user_query/3, query_normalization/3, search_planner/3, search_provider/3,
|
| 30 |
+
result_normalization/3, url_deduplication/3, content_retrieval/3,
|
| 31 |
+
content_extraction/3, source_ranking/3, result_synthesis/3,
|
| 32 |
+
frontend_visibility/3, done/3, failed/3]).
|
| 33 |
+
|
| 34 |
+
-define(MIN_ACCEPTABLE_RESULTS, 3).
|
| 35 |
+
-define(MAX_DOCS_RETRIEVED, 4).
|
| 36 |
+
|
| 37 |
+
-record(sjdata, {
|
| 38 |
+
job_id, owner_agent_id, query, max_iterations, iteration = 0,
|
| 39 |
+
provider,
|
| 40 |
+
planned_queries = [],
|
| 41 |
+
raw_results = [],
|
| 42 |
+
normalized_results = [],
|
| 43 |
+
deduped_results = [],
|
| 44 |
+
retrieved_docs = #{},
|
| 45 |
+
extracted_docs = #{},
|
| 46 |
+
ranked_results = [],
|
| 47 |
+
final_result,
|
| 48 |
+
waiter
|
| 49 |
+
}).
|
| 50 |
+
|
| 51 |
+
start_link(Args) ->
|
| 52 |
+
gen_statem:start_link(?MODULE, Args, []).
|
| 53 |
+
|
| 54 |
+
-spec run(pid()) -> ok.
|
| 55 |
+
run(Pid) ->
|
| 56 |
+
gen_statem:cast(Pid, run).
|
| 57 |
+
|
| 58 |
+
-spec await_result(pid(), timeout()) -> {ok, map()} | {error, term()}.
|
| 59 |
+
await_result(Pid, Timeout) ->
|
| 60 |
+
try gen_statem:call(Pid, await_result, Timeout)
|
| 61 |
+
catch exit:{timeout, _} -> {error, pending}
|
| 62 |
+
end.
|
| 63 |
+
|
| 64 |
+
-spec describe(pid()) -> {ok, map()}.
|
| 65 |
+
describe(Pid) ->
|
| 66 |
+
gen_statem:call(Pid, describe).
|
| 67 |
+
|
| 68 |
+
callback_mode() -> state_functions.
|
| 69 |
+
|
| 70 |
+
init(#{job_id := JobId, query := Query} = Args) ->
|
| 71 |
+
Provider = application:get_env(hyperkitty, search_provider, hk_search_provider_mock),
|
| 72 |
+
Data = #sjdata{
|
| 73 |
+
job_id = JobId,
|
| 74 |
+
owner_agent_id = maps:get(owner_agent_id, Args, undefined),
|
| 75 |
+
query = Query,
|
| 76 |
+
max_iterations = maps:get(max_iterations, Args, 3),
|
| 77 |
+
provider = Provider
|
| 78 |
+
},
|
| 79 |
+
{ok, user_query, Data}.
|
| 80 |
+
|
| 81 |
+
%%% pipeline stages
|
| 82 |
+
|
| 83 |
+
user_query(cast, run, Data) ->
|
| 84 |
+
emit(Data, user_query, <<"search.started">>, #{query => Data#sjdata.query}),
|
| 85 |
+
advance(query_normalization, Data);
|
| 86 |
+
user_query({call, From}, await_result, Data) ->
|
| 87 |
+
{keep_state, Data#sjdata{waiter = From}};
|
| 88 |
+
user_query(EventType, EventContent, Data) ->
|
| 89 |
+
common(user_query, EventType, EventContent, Data).
|
| 90 |
+
|
| 91 |
+
query_normalization(internal, go, Data) ->
|
| 92 |
+
Normalized = normalize_query(Data#sjdata.query),
|
| 93 |
+
emit(Data, query_normalization, <<"search.query_normalized">>, #{normalized => Normalized}),
|
| 94 |
+
advance(search_planner, Data#sjdata{query = Normalized});
|
| 95 |
+
query_normalization(EventType, EventContent, Data) ->
|
| 96 |
+
common(query_normalization, EventType, EventContent, Data).
|
| 97 |
+
|
| 98 |
+
search_planner(internal, go, Data) ->
|
| 99 |
+
Provider = Data#sjdata.provider,
|
| 100 |
+
case safe(fun() -> Provider:plan(Data#sjdata.query, #{iteration => Data#sjdata.iteration}) end) of
|
| 101 |
+
{ok, SubQueries} ->
|
| 102 |
+
lists:foreach(
|
| 103 |
+
fun(Q) -> emit(Data, search_planner, <<"search.query_generated">>, #{sub_query => Q}) end,
|
| 104 |
+
SubQueries),
|
| 105 |
+
advance(search_provider, Data#sjdata{planned_queries = SubQueries});
|
| 106 |
+
{error, Reason} ->
|
| 107 |
+
fail(Data, {search_planner_failed, Reason})
|
| 108 |
+
end;
|
| 109 |
+
search_planner(EventType, EventContent, Data) ->
|
| 110 |
+
common(search_planner, EventType, EventContent, Data).
|
| 111 |
+
|
| 112 |
+
search_provider(internal, go, Data) ->
|
| 113 |
+
Provider = Data#sjdata.provider,
|
| 114 |
+
Results = lists:flatmap(
|
| 115 |
+
fun(SubQuery) ->
|
| 116 |
+
emit(Data, search_provider, <<"search.provider_called">>, #{sub_query => SubQuery}),
|
| 117 |
+
case safe(fun() -> Provider:search(SubQuery, #{}) end) of
|
| 118 |
+
{ok, R} -> [maps:put(sub_query, SubQuery, Item) || Item <- R];
|
| 119 |
+
{error, _Reason} -> []
|
| 120 |
+
end
|
| 121 |
+
end,
|
| 122 |
+
Data#sjdata.planned_queries),
|
| 123 |
+
emit(Data, search_provider, <<"search.results_received">>, #{count => length(Results)}),
|
| 124 |
+
advance(result_normalization, Data#sjdata{raw_results = Data#sjdata.raw_results ++ Results});
|
| 125 |
+
search_provider(EventType, EventContent, Data) ->
|
| 126 |
+
common(search_provider, EventType, EventContent, Data).
|
| 127 |
+
|
| 128 |
+
result_normalization(internal, go, Data) ->
|
| 129 |
+
Normalized = [R#{normalized_url => hk_search_pipeline:normalize_url(maps:get(url, R))}
|
| 130 |
+
|| R <- Data#sjdata.raw_results],
|
| 131 |
+
advance(url_deduplication, Data#sjdata{normalized_results = Normalized});
|
| 132 |
+
result_normalization(EventType, EventContent, Data) ->
|
| 133 |
+
common(result_normalization, EventType, EventContent, Data).
|
| 134 |
+
|
| 135 |
+
url_deduplication(internal, go, Data) ->
|
| 136 |
+
Deduped = hk_search_pipeline:dedupe_by(normalized_url, Data#sjdata.normalized_results),
|
| 137 |
+
emit(Data, url_deduplication, <<"search.urls_deduplicated">>,
|
| 138 |
+
#{before => length(Data#sjdata.normalized_results), after_count => length(Deduped)}),
|
| 139 |
+
advance(content_retrieval, Data#sjdata{deduped_results = Deduped});
|
| 140 |
+
url_deduplication(EventType, EventContent, Data) ->
|
| 141 |
+
common(url_deduplication, EventType, EventContent, Data).
|
| 142 |
+
|
| 143 |
+
content_retrieval(internal, go, Data) ->
|
| 144 |
+
Provider = Data#sjdata.provider,
|
| 145 |
+
ToFetch = lists:sublist(Data#sjdata.deduped_results, ?MAX_DOCS_RETRIEVED),
|
| 146 |
+
Docs = lists:foldl(
|
| 147 |
+
fun(R, Acc) ->
|
| 148 |
+
Url = maps:get(url, R),
|
| 149 |
+
case safe(fun() -> Provider:fetch(Url) end) of
|
| 150 |
+
{ok, #{content_type := CT, body := Body}} ->
|
| 151 |
+
emit(Data, content_retrieval, <<"search.document_retrieved">>, #{url => Url}),
|
| 152 |
+
Doc = #source_document{document_id = hk_id:new(<<"doc">>), url = Url,
|
| 153 |
+
fetched_at_ms = hk_id:timestamp_ms(),
|
| 154 |
+
content_type = CT, extracted_text = Body,
|
| 155 |
+
citation_map = #{}},
|
| 156 |
+
Acc#{Url => Doc};
|
| 157 |
+
{error, _Reason} ->
|
| 158 |
+
Acc
|
| 159 |
+
end
|
| 160 |
+
end,
|
| 161 |
+
#{}, ToFetch),
|
| 162 |
+
advance(content_extraction, Data#sjdata{retrieved_docs = Docs});
|
| 163 |
+
content_retrieval(EventType, EventContent, Data) ->
|
| 164 |
+
common(content_retrieval, EventType, EventContent, Data).
|
| 165 |
+
|
| 166 |
+
content_extraction(internal, go, Data) ->
|
| 167 |
+
Provider = Data#sjdata.provider,
|
| 168 |
+
Extracted = maps:map(
|
| 169 |
+
fun(Url, Doc) ->
|
| 170 |
+
case safe(fun() -> Provider:extract(Doc#source_document.extracted_text,
|
| 171 |
+
Doc#source_document.content_type) end) of
|
| 172 |
+
{ok, #{text := Text, citation_map := CMap}} ->
|
| 173 |
+
emit(Data, content_extraction, <<"search.document_extracted">>, #{url => Url}),
|
| 174 |
+
Doc#source_document{extracted_text = Text, citation_map = CMap};
|
| 175 |
+
{error, _Reason} ->
|
| 176 |
+
Doc
|
| 177 |
+
end
|
| 178 |
+
end,
|
| 179 |
+
Data#sjdata.retrieved_docs),
|
| 180 |
+
advance(source_ranking, Data#sjdata{extracted_docs = Extracted});
|
| 181 |
+
content_extraction(EventType, EventContent, Data) ->
|
| 182 |
+
common(content_extraction, EventType, EventContent, Data).
|
| 183 |
+
|
| 184 |
+
source_ranking(internal, go, Data) ->
|
| 185 |
+
Ranked = hk_search_pipeline:rank_sources(Data#sjdata.deduped_results, Data#sjdata.extracted_docs,
|
| 186 |
+
Data#sjdata.job_id),
|
| 187 |
+
lists:foreach(
|
| 188 |
+
fun(#search_result{url = Url, rank = Rank}) ->
|
| 189 |
+
emit(Data, source_ranking, <<"search.source_ranked">>, #{url => Url, rank => Rank})
|
| 190 |
+
end,
|
| 191 |
+
Ranked),
|
| 192 |
+
Data2 = Data#sjdata{ranked_results = Ranked},
|
| 193 |
+
case {length(Ranked) < ?MIN_ACCEPTABLE_RESULTS, Data2#sjdata.iteration < Data2#sjdata.max_iterations - 1} of
|
| 194 |
+
{true, true} ->
|
| 195 |
+
Data3 = Data2#sjdata{iteration = Data2#sjdata.iteration + 1},
|
| 196 |
+
emit(Data3, source_ranking, <<"search.iteration_retried">>, #{iteration => Data3#sjdata.iteration}),
|
| 197 |
+
advance(search_planner, Data3);
|
| 198 |
+
_ ->
|
| 199 |
+
advance(result_synthesis, Data2)
|
| 200 |
+
end;
|
| 201 |
+
source_ranking(EventType, EventContent, Data) ->
|
| 202 |
+
common(source_ranking, EventType, EventContent, Data).
|
| 203 |
+
|
| 204 |
+
result_synthesis(internal, go, Data) ->
|
| 205 |
+
Final = #{
|
| 206 |
+
job_id => Data#sjdata.job_id,
|
| 207 |
+
query => Data#sjdata.query,
|
| 208 |
+
iterations_used => Data#sjdata.iteration + 1,
|
| 209 |
+
results => [hk_schema:to_map(R) || R <- Data#sjdata.ranked_results],
|
| 210 |
+
sources => [hk_schema:to_map(D) || D <- maps:values(Data#sjdata.extracted_docs)]
|
| 211 |
+
},
|
| 212 |
+
emit(Data, result_synthesis, <<"search.result_synthesized">>,
|
| 213 |
+
#{result_count => length(Data#sjdata.ranked_results)}),
|
| 214 |
+
advance(frontend_visibility, Data#sjdata{final_result = Final});
|
| 215 |
+
result_synthesis(EventType, EventContent, Data) ->
|
| 216 |
+
common(result_synthesis, EventType, EventContent, Data).
|
| 217 |
+
|
| 218 |
+
frontend_visibility(internal, go, Data) ->
|
| 219 |
+
emit(Data, frontend_visibility, <<"search.completed">>, #{}),
|
| 220 |
+
Replies = case Data#sjdata.waiter of
|
| 221 |
+
undefined -> [];
|
| 222 |
+
From -> [{reply, From, {ok, Data#sjdata.final_result}}]
|
| 223 |
+
end,
|
| 224 |
+
{next_state, done, Data#sjdata{waiter = undefined}, Replies};
|
| 225 |
+
frontend_visibility(EventType, EventContent, Data) ->
|
| 226 |
+
common(frontend_visibility, EventType, EventContent, Data).
|
| 227 |
+
|
| 228 |
+
done({call, From}, await_result, Data) ->
|
| 229 |
+
{keep_state_and_data, [{reply, From, {ok, Data#sjdata.final_result}}]};
|
| 230 |
+
done({call, From}, describe, Data) ->
|
| 231 |
+
{keep_state_and_data, [{reply, From, {ok, describe_map(done, Data)}}]};
|
| 232 |
+
done(_EventType, _EventContent, _Data) ->
|
| 233 |
+
keep_state_and_data.
|
| 234 |
+
|
| 235 |
+
failed({call, From}, await_result, Data) ->
|
| 236 |
+
{keep_state_and_data, [{reply, From, {error, Data#sjdata.final_result}}]};
|
| 237 |
+
failed({call, From}, describe, Data) ->
|
| 238 |
+
{keep_state_and_data, [{reply, From, {ok, describe_map(failed, Data)}}]};
|
| 239 |
+
failed(_EventType, _EventContent, _Data) ->
|
| 240 |
+
keep_state_and_data.
|
| 241 |
+
|
| 242 |
+
%%% internal
|
| 243 |
+
|
| 244 |
+
advance(NextState, Data) ->
|
| 245 |
+
{next_state, NextState, Data, [{next_event, internal, go}]}.
|
| 246 |
+
|
| 247 |
+
fail(Data, Reason) ->
|
| 248 |
+
emit(Data, failed, <<"search.failed">>, #{reason => term_bin(Reason)}),
|
| 249 |
+
Replies = case Data#sjdata.waiter of
|
| 250 |
+
undefined -> [];
|
| 251 |
+
From -> [{reply, From, {error, Reason}}]
|
| 252 |
+
end,
|
| 253 |
+
{next_state, failed, Data#sjdata{final_result = Reason, waiter = undefined}, Replies}.
|
| 254 |
+
|
| 255 |
+
common(StateName, {call, From}, describe, Data) ->
|
| 256 |
+
{keep_state_and_data, [{reply, From, {ok, describe_map(StateName, Data)}}]};
|
| 257 |
+
common(_StateName, {call, From}, await_result, Data) ->
|
| 258 |
+
{keep_state, Data#sjdata{waiter = From}};
|
| 259 |
+
common(_StateName, _EventType, _EventContent, _Data) ->
|
| 260 |
+
keep_state_and_data.
|
| 261 |
+
|
| 262 |
+
safe(Fun) ->
|
| 263 |
+
try Fun() catch Class:Reason -> {error, {Class, Reason}} end.
|
| 264 |
+
|
| 265 |
+
normalize_query(Q) ->
|
| 266 |
+
iolist_to_binary(string:trim(string:lowercase(binary_to_list(Q)))).
|
| 267 |
+
|
| 268 |
+
describe_map(StateName, Data) ->
|
| 269 |
+
#search_job{
|
| 270 |
+
job_id = Data#sjdata.job_id,
|
| 271 |
+
owner_agent_id = Data#sjdata.owner_agent_id,
|
| 272 |
+
query = Data#sjdata.query,
|
| 273 |
+
stage = StateName,
|
| 274 |
+
max_iterations = Data#sjdata.max_iterations,
|
| 275 |
+
iteration = Data#sjdata.iteration,
|
| 276 |
+
results = [R#search_result.result_id || R <- Data#sjdata.ranked_results],
|
| 277 |
+
created_at_ms = 0,
|
| 278 |
+
updated_at_ms = hk_id:timestamp_ms()
|
| 279 |
+
}.
|
| 280 |
+
|
| 281 |
+
emit(Data, Stage, Category, ExtraData) ->
|
| 282 |
+
Base = #{job_id => Data#sjdata.job_id, stage => Stage, iteration => Data#sjdata.iteration},
|
| 283 |
+
Event = hk_event:new(Category, {search_job, Data#sjdata.job_id}, maps:merge(Base, ExtraData)),
|
| 284 |
+
catch hk_event_bus:publish(Event).
|
| 285 |
+
|
| 286 |
+
term_bin(Term) ->
|
| 287 |
+
iolist_to_binary(io_lib:format("~p", [Term])).
|