1% -*- Mode: Erlang; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2
3% Licensed under the Apache License, Version 2.0 (the "License"); you may not
4% use this file except in compliance with the License. You may obtain a copy of
5% the License at
6%
7%   http://www.apache.org/licenses/LICENSE-2.0
8%
9% Unless required by applicable law or agreed to in writing, software
10% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12% License for the specific language governing permissions and limitations under
13% the License.
14
15-module(couch_set_view_updater).
16
17-export([update/6]).
18% Exported for the MapReduce specific stuff
19-export([new_sort_file_name/1]).
20
21-include("couch_db.hrl").
22-include_lib("couch_set_view/include/couch_set_view.hrl").
23-include_lib("couch_dcp/include/couch_dcp.hrl").
24
25-define(MAP_QUEUE_SIZE, 256 * 1024).
26-define(WRITE_QUEUE_SIZE, 512 * 1024).
27% The size of the accumulator the emitted key-values are queued up in before
28% they get actually queued. The bigger the value, the less the lock contention,
29% but the higher the possible memory consumption is.
30-define(QUEUE_ACC_BATCH_SIZE, 256 * 1024).
31
32% incremental updates
33-define(INC_MAX_TMP_FILE_SIZE, 31457280).
34-define(MIN_BATCH_SIZE_PER_VIEW, 65536).
35
36% For file sorter and file merger commands.
37-define(PORT_OPTS,
38        [exit_status, use_stdio, stderr_to_stdout, {line, 4096}, binary]).
39
40-record(writer_acc, {
41    parent,
42    owner,
43    group,
44    last_seqs = orddict:new(),
45    part_versions = orddict:new(),
46    compactor_running,
47    write_queue,
48    initial_build,
49    view_empty_kvs,
50    kvs = [],
51    kvs_size = 0,
52    state = updating_active,
53    final_batch = false,
54    max_seqs,
55    stats = #set_view_updater_stats{},
56    tmp_dir = nil,
57    initial_seqs,
58    max_insert_batch_size,
59    tmp_files = dict:new(),
60    throttle = 0,
61    force_flush = false
62}).
63
64
65-spec update(pid(), #set_view_group{},
66             partition_seqs(), boolean(), string(), [term()]) -> no_return().
67update(Owner, Group, CurSeqs, CompactorRunning, TmpDir, Options) ->
68    #set_view_group{
69        set_name = SetName,
70        type = Type,
71        name = DDocId
72    } = Group,
73
74    ActiveParts = couch_set_view_util:decode_bitmask(?set_abitmask(Group)),
75    PassiveParts = couch_set_view_util:decode_bitmask(?set_pbitmask(Group)),
76    NumChanges = couch_set_view_util:missing_changes_count(CurSeqs, ?set_seqs(Group)),
77
78    process_flag(trap_exit, true),
79
80    BeforeEnterTs = os:timestamp(),
81    Parent = self(),
82    BarrierEntryPid = spawn_link(fun() ->
83        DDocIds = couch_set_view_util:get_ddoc_ids_with_sig(SetName, Group),
84        couch_task_status:add_task([
85            {type, blocked_indexer},
86            {set, SetName},
87            {signature, ?l2b(couch_util:to_hex(Group#set_view_group.sig))},
88            {design_documents, DDocIds},
89            {indexer_type, Type}
90        ]),
91        case Type of
92        main ->
93            ok = couch_index_barrier:enter(couch_main_index_barrier, Parent);
94        replica ->
95            ok = couch_index_barrier:enter(couch_replica_index_barrier, Parent)
96        end,
97        Parent ! {done, self(), (timer:now_diff(os:timestamp(), BeforeEnterTs) / 1000000)},
98        receive shutdown -> ok end
99    end),
100
101    BlockedTime = receive
102    {done, BarrierEntryPid, Duration} ->
103        Duration;
104    {'EXIT', _, Reason} ->
105        exit({updater_error, Reason})
106    end,
107
108    CleanupParts = couch_set_view_util:decode_bitmask(?set_cbitmask(Group)),
109    InitialBuild = couch_set_view_util:is_initial_build(Group),
110    ?LOG_INFO("Updater for set view `~s`, ~s group `~s` started~n"
111              "Active partitions:    ~w~n"
112              "Passive partitions:   ~w~n"
113              "Cleanup partitions:   ~w~n"
114              "Replicas to transfer: ~w~n"
115              "Pending transition:   ~n"
116              "    active:           ~w~n"
117              "    passive:          ~w~n"
118              "    unindexable:      ~w~n"
119              "Initial build:        ~s~n"
120              "Compactor running:    ~s~n"
121              "Min # changes:        ~p~n"
122              "Partition versions:   ~w~n",
123              [SetName, Type, DDocId,
124               ActiveParts,
125               PassiveParts,
126               CleanupParts,
127               ?set_replicas_on_transfer(Group),
128               ?pending_transition_active(?set_pending_transition(Group)),
129               ?pending_transition_passive(?set_pending_transition(Group)),
130               ?pending_transition_unindexable(?set_pending_transition(Group)),
131               InitialBuild,
132               CompactorRunning,
133               NumChanges,
134               ?set_partition_versions(Group)
135              ]),
136
137    WriterAcc0 = #writer_acc{
138        parent = self(),
139        owner = Owner,
140        group = Group,
141        initial_build = InitialBuild,
142        max_seqs = CurSeqs,
143        part_versions = ?set_partition_versions(Group),
144        tmp_dir = TmpDir,
145        max_insert_batch_size = list_to_integer(
146            couch_config:get("set_views", "indexer_max_insert_batch_size", "1048576"))
147    },
148    update(WriterAcc0, ActiveParts, PassiveParts,
149            BlockedTime, BarrierEntryPid, NumChanges, CompactorRunning, Options).
150
151
152update(WriterAcc, ActiveParts, PassiveParts, BlockedTime,
153       BarrierEntryPid, NumChanges, CompactorRunning, Options) ->
154    #writer_acc{
155        owner = Owner,
156        group = Group
157    } = WriterAcc,
158    #set_view_group{
159        set_name = SetName,
160        type = Type,
161        name = DDocId,
162        sig = GroupSig
163    } = Group,
164
165    StartTime = os:timestamp(),
166
167    MapQueueOptions = [{max_size, ?MAP_QUEUE_SIZE}, {max_items, infinity}],
168    WriteQueueOptions = [{max_size, ?WRITE_QUEUE_SIZE}, {max_items, infinity}],
169    {ok, MapQueue} = couch_work_queue:new(MapQueueOptions),
170    {ok, WriteQueue} = couch_work_queue:new(WriteQueueOptions),
171
172    Parent = self(),
173
174    Mapper = spawn_link(fun() ->
175        try
176            do_maps(Group, MapQueue, WriteQueue)
177        catch _:Error ->
178            Stacktrace = erlang:get_stacktrace(),
179            ?LOG_ERROR("Set view `~s`, ~s group `~s`, mapper error~n"
180                "error:      ~p~n"
181                "stacktrace: ~p~n",
182                [SetName, Type, DDocId, Error, Stacktrace]),
183            exit(Error)
184        end
185    end),
186
187    Writer = spawn_link(fun() ->
188        BarrierEntryPid ! shutdown,
189        ViewEmptyKVs = [{View, []} || View <- Group#set_view_group.views],
190        WriterAcc2 = init_tmp_files(WriterAcc#writer_acc{
191            parent = Parent,
192            group = Group,
193            write_queue = WriteQueue,
194            view_empty_kvs = ViewEmptyKVs,
195            compactor_running = CompactorRunning,
196            initial_seqs = ?set_seqs(Group),
197            throttle = case lists:member(throttle, Options) of
198                true ->
199                    list_to_integer(
200                        couch_config:get("set_views", "throttle_period", "100"));
201                false ->
202                    0
203                end
204        }),
205        ok = couch_set_view_util:open_raw_read_fd(Group),
206        try
207            WriterAcc3 = do_writes(WriterAcc2),
208            receive
209            {doc_loader_finished, {PartVersions0, RealMaxSeqs}} ->
210                WriterAccStats = WriterAcc3#writer_acc.stats,
211                WriterAccGroup = WriterAcc3#writer_acc.group,
212                WriterAccHeader = WriterAccGroup#set_view_group.index_header,
213                PartVersions = lists:ukeymerge(1, PartVersions0,
214                    WriterAccHeader#set_view_index_header.partition_versions),
215                case WriterAcc3#writer_acc.initial_build of
216                true ->
217                    % The doc loader might not load the mutations up to the
218                    % most recent one, but only to a lower one. Update the
219                    % group header and stats with the correct information.
220                    MaxSeqs = lists:ukeymerge(
221                        1, RealMaxSeqs, WriterAccHeader#set_view_index_header.seqs),
222                    Stats = WriterAccStats#set_view_updater_stats{
223                        seqs = lists:sum([S || {_, S} <- RealMaxSeqs])
224                    };
225                false ->
226                    MaxSeqs = WriterAccHeader#set_view_index_header.seqs,
227                    Stats = WriterAcc3#writer_acc.stats
228                end,
229                FinalWriterAcc = WriterAcc3#writer_acc{
230                    stats = Stats,
231                    group = WriterAccGroup#set_view_group{
232                        index_header = WriterAccHeader#set_view_index_header{
233                            partition_versions = PartVersions,
234                            seqs = MaxSeqs
235                        }
236                    }
237                }
238            end,
239            Parent ! {writer_finished, FinalWriterAcc}
240        catch _:Error ->
241            Stacktrace = erlang:get_stacktrace(),
242            ?LOG_ERROR("Set view `~s`, ~s group `~s`, writer error~n"
243                "error:      ~p~n"
244                "stacktrace: ~p~n",
245                [SetName, Type, DDocId, Error, Stacktrace]),
246            exit(Error)
247        after
248            ok = couch_set_view_util:close_raw_read_fd(Group)
249        end
250    end),
251
252    InitialBuild = WriterAcc#writer_acc.initial_build,
253    NumChanges2 = case InitialBuild of
254        true ->
255            couch_set_view_updater_helper:count_items_from_set(Group, ActiveParts ++ PassiveParts);
256        false ->
257            NumChanges
258    end,
259
260    DocLoader = spawn_link(fun() ->
261        DDocIds = couch_set_view_util:get_ddoc_ids_with_sig(SetName, Group),
262        couch_task_status:add_task([
263            {type, indexer},
264            {set, SetName},
265            {signature, ?l2b(couch_util:to_hex(GroupSig))},
266            {design_documents, DDocIds},
267            {indexer_type, Type},
268            {progress, 0},
269            {changes_done, 0},
270            {initial_build, InitialBuild},
271            {total_changes, NumChanges2}
272        ]),
273        couch_task_status:set_update_frequency(5000),
274        case lists:member(pause, Options) of
275        true ->
276            % For reliable unit testing, to verify that adding new partitions
277            % to the passive state doesn't restart the updater and the updater
278            % can be aware of it and index these new partitions in the same run.
279            receive continue -> ok end;
280        false ->
281            ok
282        end,
283        try
284            {PartVersions, MaxSeqs} = load_changes(
285                Owner, Parent, Group, MapQueue, ActiveParts, PassiveParts,
286                WriterAcc#writer_acc.max_seqs,
287                WriterAcc#writer_acc.initial_build),
288            Parent ! {doc_loader_finished, {PartVersions, MaxSeqs}}
289        catch
290        throw:purge ->
291            exit(purge);
292        throw:{rollback, RollbackSeqs} ->
293            exit({rollback, RollbackSeqs});
294        _:Error ->
295            Stacktrace = erlang:get_stacktrace(),
296            ?LOG_ERROR("Set view `~s`, ~s group `~s`, doc loader error~n"
297                "error:      ~p~n"
298                "stacktrace: ~p~n",
299                [SetName, Type, DDocId, Error, Stacktrace]),
300            exit(Error)
301        end,
302        % Since updater progress stats is added from docloader,
303        % this process has to stay till updater has completed.
304        receive
305        updater_finished ->
306            ok
307        end
308    end),
309
310    Result = wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, Group),
311    case Type of
312    main ->
313        ok = couch_index_barrier:leave(couch_main_index_barrier);
314    replica ->
315        ok = couch_index_barrier:leave(couch_replica_index_barrier)
316    end,
317    case Result of
318    {updater_finished, #set_view_updater_result{group = NewGroup}} ->
319        ?LOG_DEBUG("Updater for ~s set view group `~s`, set `~s`, writer finished:~n"
320                   "  start seqs: ~w~n"
321                   "  end seqs:   ~w~n",
322                   [Type, DDocId, SetName, ?set_seqs(Group), ?set_seqs(NewGroup)]);
323    _ ->
324        ok
325    end,
326    DocLoader ! updater_finished,
327    exit(Result).
328
329
330wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup) ->
331    #set_view_group{set_name = SetName, name = DDocId, type = Type} = OldGroup,
332    receive
333    {new_passive_partitions, _} = NewPassivePartitions ->
334        Writer ! NewPassivePartitions,
335        DocLoader ! NewPassivePartitions,
336        wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup);
337    continue ->
338        % Used by unit tests.
339        DocLoader ! continue,
340        wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup);
341    {doc_loader_finished, {PartVersions, MaxSeqs}} ->
342        Writer ! {doc_loader_finished, {PartVersions, MaxSeqs}},
343        wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup);
344    {writer_finished, WriterAcc} ->
345        Stats0 = WriterAcc#writer_acc.stats,
346        Result = #set_view_updater_result{
347            group = WriterAcc#writer_acc.group,
348            state = WriterAcc#writer_acc.state,
349            stats = Stats0#set_view_updater_stats{
350                indexing_time = timer:now_diff(os:timestamp(), StartTime) / 1000000,
351                blocked_time = BlockedTime
352            },
353            tmp_file = case WriterAcc#writer_acc.initial_build of
354                true ->
355                    dict:fetch(build_file, WriterAcc#writer_acc.tmp_files);
356                false ->
357                    ""
358                end
359        },
360        {updater_finished, Result};
361    {compactor_started, Pid, Ref} ->
362        ?LOG_INFO("Set view `~s`, ~s group `~s`, updater received "
363                  "compactor ~p notification, ref ~p, writer ~p",
364                   [SetName, Type, DDocId, Pid, Ref, Writer]),
365        Writer ! {compactor_started, self()},
366        erlang:put(compactor_pid, {Pid, Ref}),
367        wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup);
368    {compactor_started_ack, Writer, GroupSnapshot} ->
369        ?LOG_INFO("Set view `~s`, ~s group `~s`, updater received compaction ack"
370                  " from writer ~p", [SetName, Type, DDocId, Writer]),
371        case erlang:erase(compactor_pid) of
372        {Pid, Ref} ->
373            Pid ! {Ref, {ok, GroupSnapshot}};
374        undefined ->
375            ok
376        end,
377        wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup);
378    {'EXIT', _, Reason} when Reason =/= normal ->
379        couch_util:shutdown_sync(DocLoader),
380        couch_util:shutdown_sync(Mapper),
381        couch_util:shutdown_sync(Writer),
382        {updater_error, Reason};
383    {native_updater_start, Writer} ->
384        % We need control over spawning native updater process
385        % This helps to terminate native os processes correctly
386        Writer ! {ok, native_updater_start},
387        receive
388        {native_updater_pid, NativeUpdater} ->
389            erlang:put(native_updater, NativeUpdater)
390        end,
391        wait_result_loop(StartTime, DocLoader, Mapper, Writer, BlockedTime, OldGroup);
392    stop ->
393        case erlang:erase(native_updater) of
394        undefined ->
395            couch_util:shutdown_sync(DocLoader),
396            couch_util:shutdown_sync(Mapper),
397            couch_util:shutdown_sync(Writer);
398        NativeUpdater ->
399            MRef = erlang:monitor(process, NativeUpdater),
400            NativeUpdater ! stop,
401            receive
402            {'DOWN', MRef, process, NativeUpdater, _} ->
403                couch_util:shutdown_sync(DocLoader),
404                couch_util:shutdown_sync(Mapper),
405                couch_util:shutdown_sync(Writer)
406            end
407        end,
408        exit({updater_error, shutdown})
409    end.
410
411
412dcp_marker_to_string(Type) ->
413    case Type band ?DCP_SNAPSHOT_TYPE_MASK of
414    ?DCP_SNAPSHOT_TYPE_DISK ->
415        "on-disk";
416    ?DCP_SNAPSHOT_TYPE_MEMORY ->
417        "in-memory";
418    _ ->
419        io_lib:format("unknown (~w)", [Type])
420    end.
421
422
423load_changes(Owner, Updater, Group, MapQueue, ActiveParts, PassiveParts,
424        EndSeqs, InitialBuild) ->
425    #set_view_group{
426        set_name = SetName,
427        name = DDocId,
428        type = GroupType,
429        index_header = #set_view_index_header{
430            seqs = SinceSeqs,
431            partition_versions = PartVersions0
432        },
433        dcp_pid = DcpPid,
434        category = Category
435    } = Group,
436
437    MaxDocSize = list_to_integer(
438        couch_config:get("set_views", "indexer_max_doc_size", "0")),
439    FoldFun = fun({PartId, EndSeq}, {AccCount, AccSeqs, AccVersions, AccRollbacks}) ->
440        case couch_set_view_util:has_part_seq(PartId, ?set_unindexable_seqs(Group))
441            andalso not lists:member(PartId, ?set_replicas_on_transfer(Group)) of
442        true ->
443            {AccCount, AccSeqs, AccVersions, AccRollbacks};
444        false ->
445            Since = couch_util:get_value(PartId, SinceSeqs, 0),
446            PartVersions = couch_util:get_value(PartId, AccVersions),
447            Flags = case InitialBuild of
448            true ->
449                ?DCP_FLAG_DISKONLY;
450            false ->
451                ?DCP_FLAG_NOFLAG
452            end,
453            % For stream request from 0, If a vbucket got reset in the window
454            % of time between seqno was obtained from stats and stream request
455            % was made, the end_seqno may be higher than current vb high seqno.
456            % Use a special flag to tell server to set end_seqno.
457            Flags2 = case PartVersions of
458            [{0, 0}] ->
459                Flags bor ?DCP_FLAG_USELATEST_ENDSEQNO;
460            _ ->
461                Flags
462            end,
463
464            case AccRollbacks of
465            [] ->
466                case EndSeq =:= Since of
467                true ->
468                    {AccCount, AccSeqs, AccVersions, AccRollbacks};
469                false ->
470                    ChangesWrapper = fun
471                        ({part_versions, _} = NewVersions, Acc) ->
472                            queue_doc(
473                                NewVersions, MapQueue, Group,
474                                MaxDocSize, InitialBuild),
475                            Acc;
476                        ({snapshot_marker, {MarkerStartSeq, MarkerEndSeq, MarkerType}}, {Count, _})
477                            when MarkerType band ?DCP_SNAPSHOT_TYPE_MASK =/= 0 ->
478                            ?LOG_INFO(
479                                "set view `~s`, ~s (~s) group `~s`: received "
480                                "a snapshot marker (~s) for partition ~p from "
481                                "sequence ~p to ~p",
482                                [SetName, GroupType, Category, DDocId,
483                                    dcp_marker_to_string(MarkerType),
484                                    PartId, MarkerStartSeq, MarkerEndSeq]),
485                            case Count of
486                            % Ignore the snapshot marker that is at the
487                            % beginning of the stream.
488                            % If it wasn't ignored, it would lead to an
489                            % additional forced flush which isn't needed. A
490                            % flush is needed if there are several mutations
491                            % of the same document within one batch. As two
492                            % different partitions can't contain the same
493                            % document ID, we are safe to not force flushing
494                            % between two partitions.
495                            0 ->
496                                {Count, MarkerEndSeq};
497                            _ ->
498                                queue_doc(
499                                    snapshot_marker, MapQueue, Group,
500                                    MaxDocSize, InitialBuild),
501                                {Count, MarkerEndSeq}
502                            end;
503                        ({snapshot_marker, {MarkerStartSeq, MarkerEndSeq, MarkerType}}, Acc) ->
504                            ?LOG_ERROR(
505                                "set view `~s`, ~s (~s) group `~s`: received "
506                                "a snapshot marker (~s) for partition ~p from "
507                                "sequence ~p to ~p",
508                                [SetName, GroupType, Category, DDocId,
509                                    dcp_marker_to_string(MarkerType),
510                                    PartId, MarkerStartSeq, MarkerEndSeq]),
511                            throw({error, unknown_snapshot_marker, MarkerType}),
512                            Acc;
513                        (#dcp_doc{} = Item, {Count, AccEndSeq}) ->
514                            queue_doc(
515                                Item, MapQueue, Group,
516                                MaxDocSize, InitialBuild),
517                            {Count + 1, AccEndSeq}
518                        end,
519                    Result = couch_dcp_client:enum_docs_since(
520                        DcpPid, PartId, PartVersions, Since, EndSeq, Flags2,
521                        ChangesWrapper, {0, 0}),
522                    case Result of
523                    {ok, {AccCount2, AccEndSeq}, NewPartVersions} ->
524                        AccSeqs2 = orddict:store(PartId, AccEndSeq, AccSeqs),
525                        AccVersions2 = lists:ukeymerge(
526                            1, [{PartId, NewPartVersions}], AccVersions),
527                        AccRollbacks2 = AccRollbacks;
528                    {rollback, RollbackSeq} ->
529                        AccCount2 = AccCount,
530                        AccSeqs2 = AccSeqs,
531                        AccVersions2 = AccVersions,
532                        AccRollbacks2 = ordsets:add_element(
533                            {PartId, RollbackSeq}, AccRollbacks);
534                    Error ->
535                        AccCount2 = AccCount,
536                        AccSeqs2 = AccSeqs,
537                        AccVersions2 = AccVersions,
538                        AccRollbacks2 = AccRollbacks,
539                        ?LOG_ERROR("set view `~s`, ~s (~s) group `~s` error"
540                            "while loading changes for partition ~p:~n~p~n",
541                            [SetName, GroupType, Category, DDocId, PartId,
542                                Error]),
543                        throw(Error)
544                    end,
545                    {AccCount2, AccSeqs2, AccVersions2, AccRollbacks2}
546                end;
547            _ ->
548                % If there is a rollback needed, don't store any new documents
549                % in the index, but just check for a rollback of another
550                % partition (i.e. a request with start seq == end seq)
551                ChangesWrapper = fun(_, _) -> ok end,
552                Result = couch_dcp_client:enum_docs_since(
553                    DcpPid, PartId, PartVersions, Since, Since, Flags2,
554                    ChangesWrapper, ok),
555                case Result of
556                {ok, _, _} ->
557                    AccRollbacks2 = AccRollbacks;
558                {rollback, RollbackSeq} ->
559                    AccRollbacks2 = ordsets:add_element(
560                        {PartId, RollbackSeq}, AccRollbacks)
561                end,
562                {AccCount, AccSeqs, AccVersions, AccRollbacks2}
563            end
564        end
565    end,
566
567    notify_owner(Owner, {state, updating_active}, Updater),
568    case ActiveParts of
569    [] ->
570        ActiveChangesCount = 0,
571        MaxSeqs = orddict:new(),
572        PartVersions = PartVersions0,
573        Rollbacks = [];
574    _ ->
575        ?LOG_INFO("Updater reading changes from active partitions to "
576                  "update ~s set view group `~s` from set `~s`",
577                  [GroupType, DDocId, SetName]),
578        {ActiveChangesCount, MaxSeqs, PartVersions, Rollbacks} = lists:foldl(
579            FoldFun, {0, orddict:new(), PartVersions0, ordsets:new()},
580            couch_set_view_util:filter_seqs(ActiveParts, EndSeqs))
581    end,
582    case PassiveParts of
583    [] ->
584        FinalChangesCount = ActiveChangesCount,
585        MaxSeqs2 = MaxSeqs,
586        PartVersions2 = PartVersions,
587        Rollbacks2 = Rollbacks;
588    _ ->
589        ?LOG_INFO("Updater reading changes from passive partitions to "
590                  "update ~s set view group `~s` from set `~s`",
591                  [GroupType, DDocId, SetName]),
592        {FinalChangesCount, MaxSeqs2, PartVersions2, Rollbacks2} = lists:foldl(
593            FoldFun, {ActiveChangesCount, MaxSeqs, PartVersions, Rollbacks},
594            couch_set_view_util:filter_seqs(PassiveParts, EndSeqs))
595    end,
596    {FinalChangesCount3, MaxSeqs3, PartVersions3, Rollbacks3} =
597        load_changes_from_passive_parts_in_mailbox(DcpPid,
598            Group, FoldFun, FinalChangesCount, MaxSeqs2, PartVersions2, Rollbacks2),
599
600    case Rollbacks3 of
601    [] ->
602        ok;
603    _ ->
604        throw({rollback, Rollbacks3})
605    end,
606
607    couch_work_queue:close(MapQueue),
608    ?LOG_INFO("Updater for ~s set view group `~s`, set `~s` (~s), "
609              "read a total of ~p changes",
610              [GroupType, DDocId, SetName, Category, FinalChangesCount3]),
611    ?LOG_DEBUG("Updater for ~s set view group `~s`, set `~s`, max partition seqs found:~n~w",
612               [GroupType, DDocId, SetName, MaxSeqs3]),
613    {PartVersions3, MaxSeqs3}.
614
615
616load_changes_from_passive_parts_in_mailbox(DcpPid,
617        Group, FoldFun, ChangesCount, MaxSeqs0, PartVersions0, Rollbacks) ->
618    #set_view_group{
619        set_name = SetName,
620        name = DDocId,
621        type = GroupType
622    } = Group,
623    receive
624    {new_passive_partitions, Parts0} ->
625        Parts = get_more_passive_partitions(Parts0),
626        AddPartVersions = [{P, [{0, 0}]} || P <- Parts],
627        {ok, AddMaxSeqs} = couch_dcp_client:get_seqs(DcpPid, Parts),
628        PartVersions = lists:ukeymerge(1, AddPartVersions, PartVersions0),
629
630        MaxSeqs = lists:ukeymerge(1, AddMaxSeqs, MaxSeqs0),
631        ?LOG_INFO("Updater reading changes from new passive partitions ~w to "
632                  "update ~s set view group `~s` from set `~s`",
633                  [Parts, GroupType, DDocId, SetName]),
634        {ChangesCount2, MaxSeqs2, PartVersions2, Rollbacks2} = lists:foldl(
635            FoldFun, {ChangesCount, MaxSeqs, PartVersions, Rollbacks}, AddMaxSeqs),
636        load_changes_from_passive_parts_in_mailbox(DcpPid,
637            Group, FoldFun, ChangesCount2, MaxSeqs2, PartVersions2, Rollbacks2)
638    after 0 ->
639        {ChangesCount, MaxSeqs0, PartVersions0, Rollbacks}
640    end.
641
642
643get_more_passive_partitions(Parts) ->
644    receive
645    {new_passive_partitions, Parts2} ->
646        get_more_passive_partitions(Parts ++ Parts2)
647    after 0 ->
648        lists:sort(Parts)
649    end.
650
651
652notify_owner(Owner, Msg, UpdaterPid) ->
653    Owner ! {updater_info, UpdaterPid, Msg}.
654
655
656queue_doc(snapshot_marker, MapQueue, _Group, _MaxDocSize, _InitialBuild) ->
657    couch_work_queue:queue(MapQueue, snapshot_marker);
658queue_doc({part_versions, _} = PartVersions, MapQueue, _Group, _MaxDocSize,
659    _InitialBuild) ->
660    couch_work_queue:queue(MapQueue, PartVersions);
661queue_doc(Doc, MapQueue, Group, MaxDocSize, InitialBuild) ->
662    Doc2 = case Doc#dcp_doc.deleted of
663    true ->
664        case Group#set_view_group.index_xattr_on_deleted_docs of
665        true ->
666            case Doc#dcp_doc.body of
667            <<>> ->
668                Doc#dcp_doc{deleted = true};
669            _ ->
670                Doc#dcp_doc{deleted = false}
671            end;
672        false ->
673            Doc
674        end;
675    false ->
676        Doc
677    end,
678
679    case Doc2#dcp_doc.deleted of
680    true when InitialBuild ->
681        Entry = nil;
682    true ->
683        Entry = Doc2;
684    false ->
685        #set_view_group{
686           set_name = SetName,
687           name = DDocId,
688           type = GroupType
689        } = Group,
690        case couch_util:validate_utf8(Doc2#dcp_doc.id) of
691        true ->
692            case (MaxDocSize > 0) andalso
693                (iolist_size(Doc2#dcp_doc.body) > MaxDocSize) of
694            true ->
695                ?LOG_MAPREDUCE_ERROR("Bucket `~s`, ~s group `~s`, skipping "
696                    "document with ID `~s`: too large body (~p bytes)",
697                    [SetName, GroupType, DDocId,
698                     ?b2l(Doc2#dcp_doc.id), iolist_size(Doc2#dcp_doc.body)]),
699                Entry = Doc2#dcp_doc{deleted = true};
700            false ->
701                Entry = Doc2
702            end;
703        false ->
704            % If the id isn't utf8 (memcached allows it), then log an error
705            % message and skip the doc. Send it through the queue anyway
706            % so we record the high seq num in case there are a bunch of
707            % these at the end, we want to keep track of the high seq and
708            % not reprocess again.
709            ?LOG_MAPREDUCE_ERROR("Bucket `~s`, ~s group `~s`, skipping "
710                "document with non-utf8 id. Doc id bytes: ~w",
711                [SetName, GroupType, DDocId, ?b2l(Doc2#dcp_doc.id)]),
712            Entry = Doc2#dcp_doc{deleted = true}
713        end
714    end,
715    case Entry of
716    nil ->
717        ok;
718    _ ->
719        couch_work_queue:queue(MapQueue, Entry),
720        update_task(1)
721    end.
722
723-spec accumulate_xattr(binary(), binary(), non_neg_integer(), non_neg_integer()) ->
724    {binary(), binary()}.
725accumulate_xattr(Data, Acc, XATTRSize, AccSum) when AccSum =:= XATTRSize ->
726    {Data, <<Acc/binary, "}">>};
727accumulate_xattr(Body, Acc, XATTRSize, AccSum) ->
728    <<DataSize:32, Rest/binary>> = Body,
729    AccSum2 = AccSum + DataSize + 4,
730    <<Data0:DataSize/binary, Rest2/binary>> = Rest,
731    % Remove last zero value from  XATTR
732    Data = binary:part(Data0, 0, DataSize-1),
733    % Jsonify key and value
734    Data2 = case AccSum2 of
735    XATTRSize ->
736        <<"\"", Data/binary>>;
737    _ ->
738        <<"\"", Data/binary, ",">>
739    end,
740    % Replace zero byte after key with colon
741    Xattr = binary:replace(Data2, <<0>>, <<"\":">>),
742    accumulate_xattr(Rest2, <<Acc/binary, Xattr/binary>>, XATTRSize, AccSum2).
743
744do_maps(Group, MapQueue, WriteQueue) ->
745    #set_view_group{
746        set_name = SetName,
747        name = DDocId,
748        type = Type,
749        mod = Mod
750    } = Group,
751    case couch_work_queue:dequeue(MapQueue) of
752    closed ->
753        couch_work_queue:close(WriteQueue);
754    {ok, Queue, _QueueSize} ->
755        ViewCount = length(Group#set_view_group.views),
756        {Items, _} = lists:foldl(
757            fun(#dcp_doc{deleted = true} = DcpDoc, {Acc, Size}) ->
758                #dcp_doc{
759                    id = Id,
760                    partition = PartId,
761                    seq = Seq
762                } = DcpDoc,
763                Item = {Seq, Id, PartId, []},
764                {[Item | Acc], Size};
765            (#dcp_doc{deleted = false} = DcpDoc, {Acc0, Size0}) ->
766                % When there are a lot of emits per document the memory can
767                % grow almost indefinitely as the queue size is only limited
768                % by the number of documents and not their emits.
769                % In case the accumulator grows huge, queue the items early
770                % into the writer queue. Only take emits into account, the
771                % other cases in this `foldl` won't ever have an significant
772                % size.
773                {Acc, Size} = case Size0 > ?QUEUE_ACC_BATCH_SIZE of
774                true ->
775                    couch_work_queue:queue(WriteQueue, lists:reverse(Acc0)),
776                    {[], 0};
777                false ->
778                    {Acc0, Size0}
779                end,
780                #dcp_doc{
781                    id = Id,
782                    body = Body,
783                    partition = PartId,
784                    rev_seq = RevSeq,
785                    seq = Seq,
786                    cas = Cas,
787                    expiration = Expiration,
788                    flags = Flags,
789                    data_type = DcpDataType
790                } = DcpDoc,
791                {DataType, DocBody, XATTRs} = case DcpDataType of
792                ?DCP_DATA_TYPE_RAW ->
793                    {DocBody2, XATTRs2} = accumulate_xattr(Body, <<"\"xattrs\":{">>, 0, 0),
794                    {?CONTENT_META_NON_JSON_MODE, DocBody2, XATTRs2};
795                ?DCP_DATA_TYPE_JSON ->
796                    {DocBody3, XATTRs3} = accumulate_xattr(Body, <<"\"xattrs\":{">>, 0, 0),
797                    {?CONTENT_META_JSON, DocBody3, XATTRs3};
798                ?DCP_DATA_TYPE_BINARY_XATTR ->
799                    <<XATTRSize:32, Rest/binary>> = Body,
800                    {DocBody4, XATTRs4} = accumulate_xattr(Rest, <<"\"xattrs\":{">>, XATTRSize, 0),
801                    {?CONTENT_META_NON_JSON_MODE, DocBody4, XATTRs4};
802                ?DCP_DATA_TYPE_JSON_XATTR ->
803                    <<XATTRSize:32, Rest/binary>> = Body,
804                    {DocBody5, XATTRs5} = accumulate_xattr(Rest, <<"\"xattrs\":{">>, XATTRSize, 0),
805                    {?CONTENT_META_JSON, DocBody5, XATTRs5}
806                end,
807                Doc = #doc{
808                    id = Id,
809                    rev = {RevSeq, <<Cas:64, Expiration:32, Flags:32>>},
810                    body = DocBody,
811                    content_meta = DataType,
812                    deleted = false
813                },
814                try
815                    {ok, Result, LogList} = couch_set_view_mapreduce:map(
816                        Doc, XATTRs, PartId, Seq, Group),
817                    {Result2, _} = lists:foldr(
818                        fun({error, Reason}, {AccRes, Pos}) ->
819                            ErrorMsg = "Bucket `~s`, ~s group `~s`, error mapping"
820                                    " document `~s` for view `~s`: ~s",
821                            ViewName = Mod:view_name(Group, Pos),
822                            Args = [SetName, Type, DDocId, Id, ViewName,
823                                    couch_util:to_binary(Reason)],
824                            ?LOG_MAPREDUCE_ERROR(ErrorMsg, Args),
825                            {[[] | AccRes], Pos - 1};
826                        (KVs, {AccRes, Pos}) ->
827                            {[KVs | AccRes], Pos - 1}
828                        end,
829                        {[], ViewCount}, Result),
830                    lists:foreach(
831                        fun(Msg) ->
832                            DebugMsg = "Bucket `~s`, ~s group `~s`, map function"
833                                " log for document `~s`: ~s",
834                            Args = [SetName, Type, DDocId, Id, binary_to_list(Msg)],
835                            ?LOG_MAPREDUCE_ERROR(DebugMsg, Args)
836                        end, LogList),
837                    Item = {Seq, Id, PartId, Result2},
838                    {[Item | Acc], Size + erlang:external_size(Result2)}
839                catch _:{error, Reason} ->
840                    ErrorMsg = "Bucket `~s`, ~s group `~s`, error mapping document `~s`: ~s",
841                    Args = [SetName, Type, DDocId, Id, couch_util:to_binary(Reason)],
842                    ?LOG_MAPREDUCE_ERROR(ErrorMsg, Args),
843                    {[{Seq, Id, PartId, []} | Acc], Size}
844                end;
845            (snapshot_marker, {Acc, Size}) ->
846                {[snapshot_marker | Acc], Size};
847            ({part_versions, _} = PartVersions, {Acc, Size}) ->
848                {[PartVersions | Acc], Size}
849            end,
850            {[], 0}, Queue),
851        ok = couch_work_queue:queue(WriteQueue, lists:reverse(Items)),
852        do_maps(Group, MapQueue, WriteQueue)
853    end.
854
855
856do_writes(Acc) ->
857    #writer_acc{
858        kvs = Kvs,
859        kvs_size = KvsSize,
860        write_queue = WriteQueue,
861        throttle = Throttle
862    } = Acc,
863    ok = timer:sleep(Throttle),
864    case couch_work_queue:dequeue(WriteQueue) of
865    closed ->
866        flush_writes(Acc#writer_acc{final_batch = true});
867    {ok, Queue0, QueueSize} ->
868        Queue = lists:flatten(Queue0),
869        Kvs2 = Kvs ++ Queue,
870        KvsSize2 = KvsSize + QueueSize,
871
872        Acc2 = Acc#writer_acc{
873            kvs = Kvs2,
874            kvs_size = KvsSize2
875        },
876        case should_flush_writes(Acc2) of
877        true ->
878            Acc3 = flush_writes(Acc2),
879            Acc4 = Acc3#writer_acc{kvs = [], kvs_size = 0};
880        false ->
881            Acc4 = Acc2
882        end,
883        do_writes(Acc4)
884    end.
885
886should_flush_writes(Acc) ->
887    #writer_acc{
888        view_empty_kvs = ViewEmptyKvs,
889        kvs_size = KvsSize
890    } = Acc,
891    KvsSize >= (?MIN_BATCH_SIZE_PER_VIEW * length(ViewEmptyKvs)).
892
893
894flush_writes(#writer_acc{kvs = [], initial_build = false} = Acc) ->
895    Acc2 = maybe_update_btrees(Acc),
896    checkpoint(Acc2);
897
898flush_writes(#writer_acc{initial_build = false} = Acc0) ->
899    #writer_acc{
900        kvs = Kvs,
901        view_empty_kvs = ViewEmptyKVs,
902        group = Group,
903        parent = Parent,
904        owner = Owner,
905        final_batch = IsFinalBatch,
906        part_versions = PartVersions
907    } = Acc0,
908    Mod = Group#set_view_group.mod,
909    % Only incremental updates can contain multiple snapshots
910    {MultipleSnapshots, Kvs2} = merge_snapshots(Kvs),
911    Acc1 = case MultipleSnapshots of
912    true ->
913        Acc2 = maybe_update_btrees(Acc0#writer_acc{force_flush = true}),
914        checkpoint(Acc2);
915    false ->
916        Acc0
917    end,
918    #writer_acc{last_seqs = LastSeqs} = Acc1,
919    {ViewKVs, DocIdViewIdKeys, NewLastSeqs, NewPartVersions} =
920        process_map_results(Mod, Kvs2, ViewEmptyKVs, LastSeqs, PartVersions),
921    Acc3 = Acc1#writer_acc{last_seqs = NewLastSeqs, part_versions = NewPartVersions},
922    Acc4 = write_to_tmp_batch_files(ViewKVs, DocIdViewIdKeys, Acc3),
923    #writer_acc{group = NewGroup} = Acc4,
924    case ?set_seqs(NewGroup) =/= ?set_seqs(Group) of
925    true ->
926        Acc5 = checkpoint(Acc4),
927        case (Acc4#writer_acc.state =:= updating_active) andalso
928            lists:any(fun({PartId, _}) ->
929                ((1 bsl PartId) band ?set_pbitmask(Group) =/= 0)
930            end, NewLastSeqs) of
931        true ->
932            notify_owner(Owner, {state, updating_passive}, Parent),
933            Acc5#writer_acc{state = updating_passive};
934        false ->
935            Acc5
936        end;
937    false ->
938        case IsFinalBatch of
939        true ->
940            checkpoint(Acc4);
941        false ->
942            Acc4
943        end
944    end;
945
946flush_writes(#writer_acc{initial_build = true} = WriterAcc) ->
947    #writer_acc{
948        kvs = Kvs,
949        view_empty_kvs = ViewEmptyKVs,
950        tmp_files = TmpFiles,
951        tmp_dir = TmpDir,
952        group = Group,
953        final_batch = IsFinalBatch,
954        max_seqs = MaxSeqs,
955        part_versions = PartVersions,
956        stats = Stats
957    } = WriterAcc,
958    #set_view_group{
959        set_name = SetName,
960        type = Type,
961        name = DDocId,
962        mod = Mod
963    } = Group,
964    {ViewKVs, DocIdViewIdKeys, MaxSeqs2, PartVersions2} = process_map_results(
965        Mod, Kvs, ViewEmptyKVs, MaxSeqs, PartVersions),
966
967    IdRecords = lists:foldr(
968        fun({_DocId, {_PartId, []}}, Acc) ->
969                Acc;
970            (Kv, Acc) ->
971                [{KeyBin, ValBin}] = Mod:convert_back_index_kvs_to_binary([Kv], []),
972                KvBin = [<<(byte_size(KeyBin)):16>>, KeyBin, ValBin],
973                [[<<(iolist_size(KvBin)):32/native>>, KvBin] | Acc]
974        end,
975        [], DocIdViewIdKeys),
976    #set_view_tmp_file_info{fd = IdFd} = dict:fetch(ids_index, TmpFiles),
977    ok = file:write(IdFd, IdRecords),
978
979    {InsertKVCount, TmpFiles2} = Mod:write_kvs(Group, TmpFiles, ViewKVs),
980
981    Stats2 = Stats#set_view_updater_stats{
982        inserted_kvs = Stats#set_view_updater_stats.inserted_kvs + InsertKVCount,
983        inserted_ids = Stats#set_view_updater_stats.inserted_ids + length(DocIdViewIdKeys)
984    },
985    case IsFinalBatch of
986    false ->
987        WriterAcc#writer_acc{
988            max_seqs = MaxSeqs2,
989            stats = Stats2,
990            tmp_files = TmpFiles2
991        };
992    true ->
993        ?LOG_INFO("Updater for set view `~s`, ~s group `~s`, starting btree "
994                  "build phase" , [SetName, Type, DDocId]),
995        {Group2, BuildFd} = Mod:finish_build(Group, TmpFiles2, TmpDir),
996        WriterAcc#writer_acc{
997            tmp_files = dict:store(build_file, BuildFd, TmpFiles2),
998            max_seqs = MaxSeqs2,
999            part_versions = PartVersions2,
1000            stats = Stats2,
1001            group = Group2
1002        }
1003    end.
1004
1005
1006process_map_results(Mod, Kvs, ViewEmptyKVs, PartSeqs, PartVersions) ->
1007    lists:foldl(
1008        fun({Seq, DocId, PartId, []}, {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions}) ->
1009            PartIdSeqs2 = update_part_seq(Seq, PartId, PartIdSeqs),
1010            {ViewKVsAcc, [{DocId, {PartId, []}} | DocIdViewIdKeysAcc], PartIdSeqs2, PartIdVersions};
1011        ({Seq, DocId, PartId, QueryResults}, {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions}) ->
1012            {NewViewKVs, NewViewIdKeys} = Mod:view_insert_doc_query_results(
1013                    DocId, PartId, QueryResults, ViewKVsAcc, [], []),
1014            PartIdSeqs2 = update_part_seq(Seq, PartId, PartIdSeqs),
1015            {NewViewKVs, [{DocId, {PartId, NewViewIdKeys}} | DocIdViewIdKeysAcc], PartIdSeqs2, PartIdVersions};
1016        (snapshot_marker, _Acc) ->
1017            throw({error,
1018                <<"The multiple snapshots should have been merged, "
1019                  "but theu weren't">>});
1020        ({part_versions, {PartId, NewVersions}}, {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions}) ->
1021            PartIdVersions2 = update_part_versions(NewVersions, PartId, PartIdVersions),
1022            {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions2}
1023        end,
1024        {ViewEmptyKVs, [], PartSeqs, PartVersions}, Kvs).
1025
1026
1027-spec update_transferred_replicas(#set_view_group{},
1028                                  partition_seqs(),
1029                                  partition_seqs()) -> #set_view_group{}.
1030update_transferred_replicas(Group, _MaxSeqs, _PartIdSeqs) when ?set_replicas_on_transfer(Group) =:= [] ->
1031    Group;
1032update_transferred_replicas(Group, MaxSeqs, PartIdSeqs) ->
1033    #set_view_group{index_header = Header} = Group,
1034    RepsTransferred = lists:foldl(
1035        fun({PartId, Seq}, A) ->
1036            case lists:member(PartId, ?set_replicas_on_transfer(Group))
1037                andalso (Seq >= couch_set_view_util:get_part_seq(PartId, MaxSeqs)) of
1038            true ->
1039                ordsets:add_element(PartId, A);
1040            false ->
1041                A
1042            end
1043        end,
1044        ordsets:new(), PartIdSeqs),
1045    ReplicasOnTransfer2 = ordsets:subtract(?set_replicas_on_transfer(Group), RepsTransferred),
1046    {Abitmask2, Pbitmask2} = lists:foldl(
1047        fun(Id, {A, P}) ->
1048            Mask = 1 bsl Id,
1049            Mask = ?set_pbitmask(Group) band Mask,
1050            0 = ?set_abitmask(Group) band Mask,
1051            {A bor Mask, P bxor Mask}
1052        end,
1053        {?set_abitmask(Group), ?set_pbitmask(Group)},
1054        RepsTransferred),
1055    Group#set_view_group{
1056        index_header = Header#set_view_index_header{
1057            abitmask = Abitmask2,
1058            pbitmask = Pbitmask2,
1059            replicas_on_transfer = ReplicasOnTransfer2
1060        }
1061    }.
1062
1063
1064-spec update_part_seq(update_seq(), partition_id(), partition_seqs()) -> partition_seqs().
1065update_part_seq(Seq, PartId, Acc) ->
1066    case couch_set_view_util:find_part_seq(PartId, Acc) of
1067    {ok, Max} when Max >= Seq ->
1068        Acc;
1069    _ ->
1070        orddict:store(PartId, Seq, Acc)
1071    end.
1072
1073
1074-spec update_part_versions(partition_version(), partition_id(), partition_versions()) ->
1075    partition_versions().
1076update_part_versions(NewVersions, PartId, PartVersions) ->
1077    orddict:store(PartId, NewVersions, PartVersions).
1078
1079
1080% Incremental updates.
1081write_to_tmp_batch_files(ViewKeyValuesToAdd, DocIdViewIdKeys, WriterAcc) ->
1082    #writer_acc{
1083        tmp_files = TmpFiles,
1084        group = #set_view_group{
1085            id_btree = IdBtree,
1086            mod = Mod
1087        }
1088    } = WriterAcc,
1089
1090    {AddDocIdViewIdKeys0, RemoveDocIds, LookupDocIds} = lists:foldr(
1091        fun({DocId, {PartId, [] = _ViewIdKeys}}, {A, B, C}) ->
1092                BackKey = make_back_index_key(DocId, PartId),
1093                case is_new_partition(PartId, WriterAcc) of
1094                true ->
1095                    {A, [BackKey | B], C};
1096                false ->
1097                    {A, [BackKey | B], [BackKey | C]}
1098                end;
1099            ({DocId, {PartId, _ViewIdKeys}} = KvPairs, {A, B, C}) ->
1100                BackKey = make_back_index_key(DocId, PartId),
1101                case is_new_partition(PartId, WriterAcc) of
1102                true ->
1103                    {[KvPairs | A], B, C};
1104                false ->
1105                    {[KvPairs | A], B, [BackKey | C]}
1106                end
1107        end,
1108        {[], [], []}, DocIdViewIdKeys),
1109
1110    AddDocIdViewIdKeys = Mod:convert_back_index_kvs_to_binary(
1111        AddDocIdViewIdKeys0, []),
1112
1113    IdsData1 = lists:map(
1114        fun(K) -> couch_set_view_updater_helper:encode_op(remove, K) end,
1115        RemoveDocIds),
1116
1117    IdsData2 = lists:foldl(
1118        fun({K, V}, Acc) ->
1119            Bin = couch_set_view_updater_helper:encode_op(insert, K, V),
1120            [Bin | Acc]
1121        end,
1122        IdsData1,
1123        AddDocIdViewIdKeys),
1124
1125    IdTmpFileInfo = dict:fetch(ids_index, TmpFiles),
1126    case IdTmpFileInfo of
1127    #set_view_tmp_file_info{fd = nil} ->
1128        0 = IdTmpFileInfo#set_view_tmp_file_info.size,
1129        IdTmpFilePath = new_sort_file_name(WriterAcc),
1130        {ok, IdTmpFileFd} = file2:open(IdTmpFilePath, [raw, append, binary]),
1131        IdTmpFileSize = 0;
1132    #set_view_tmp_file_info{
1133            fd = IdTmpFileFd, name = IdTmpFilePath, size = IdTmpFileSize} ->
1134        ok
1135    end,
1136
1137    ok = file:write(IdTmpFileFd, IdsData2),
1138
1139    IdTmpFileInfo2 = IdTmpFileInfo#set_view_tmp_file_info{
1140        fd = IdTmpFileFd,
1141        name = IdTmpFilePath,
1142        size = IdTmpFileSize + iolist_size(IdsData2)
1143    },
1144    TmpFiles2 = dict:store(ids_index, IdTmpFileInfo2, TmpFiles),
1145
1146    case LookupDocIds of
1147    [] ->
1148        LookupResults = [];
1149    _ ->
1150        {ok, LookupResults, IdBtree} =
1151            couch_btree:query_modify(IdBtree, LookupDocIds, [], [])
1152    end,
1153    KeysToRemoveByView = lists:foldl(
1154        fun(LookupResult, KeysToRemoveByViewAcc) ->
1155            case LookupResult of
1156            {ok, {<<_Part:16, DocId/binary>>, <<_Part:16, ViewIdKeys/binary>>}} ->
1157                lists:foldl(
1158                    fun({ViewId, Keys}, KeysToRemoveByViewAcc2) ->
1159                        RemoveKeysDict = lists:foldl(
1160                            fun(Key, RemoveKeysDictAcc) ->
1161                                EncodedKey = Mod:encode_key_docid(Key, DocId),
1162                                dict:store(EncodedKey, nil, RemoveKeysDictAcc)
1163                            end,
1164                        couch_util:dict_find(ViewId, KeysToRemoveByViewAcc2, dict:new()), Keys),
1165                        dict:store(ViewId, RemoveKeysDict, KeysToRemoveByViewAcc2)
1166                    end,
1167                    KeysToRemoveByViewAcc, couch_set_view_util:parse_view_id_keys(ViewIdKeys));
1168            {not_found, _} ->
1169                KeysToRemoveByViewAcc
1170            end
1171        end,
1172        dict:new(), LookupResults),
1173
1174    WriterAcc2 = update_tmp_files(
1175        Mod, WriterAcc#writer_acc{tmp_files = TmpFiles2}, ViewKeyValuesToAdd,
1176        KeysToRemoveByView),
1177    maybe_update_btrees(WriterAcc2).
1178
1179
1180% Update the temporary files with the key-values from the indexer. Return
1181% the updated writer accumulator.
1182-spec update_tmp_files(atom(), #writer_acc{},
1183                       [{#set_view{}, [set_view_key_value()]}],
1184                       dict:dict(non_neg_integer(), dict:dict(binary(), nil)))
1185                      -> #writer_acc{}.
1186update_tmp_files(Mod, WriterAcc, ViewKeyValues, KeysToRemoveByView) ->
1187    #writer_acc{
1188       group = Group,
1189       tmp_files = TmpFiles
1190    } = WriterAcc,
1191    TmpFiles2 = lists:foldl(
1192        fun({#set_view{id_num = ViewId}, AddKeyValues}, AccTmpFiles) ->
1193            AddKeyValuesBinaries = Mod:convert_primary_index_kvs_to_binary(
1194                AddKeyValues, Group, []),
1195            KeysToRemoveDict = couch_util:dict_find(
1196                ViewId, KeysToRemoveByView, dict:new()),
1197
1198            case Mod of
1199            % The b-tree replaces nodes with the same key, hence we don't
1200            % need to delete a node that gets updated anyway
1201            mapreduce_view ->
1202                {KeysToRemoveDict2, BatchData} = lists:foldl(
1203                    fun({K, V}, {KeysToRemoveAcc, BinOpAcc}) ->
1204                        Bin = couch_set_view_updater_helper:encode_op(
1205                            insert, K, V),
1206                        BinOpAcc2 = [Bin | BinOpAcc],
1207                        case dict:find(K, KeysToRemoveAcc) of
1208                        {ok, _} ->
1209                            {dict:erase(K, KeysToRemoveAcc), BinOpAcc2};
1210                        _ ->
1211                            {KeysToRemoveAcc, BinOpAcc2}
1212                        end
1213                    end,
1214                    {KeysToRemoveDict, []}, AddKeyValuesBinaries);
1215            % In r-trees there are multiple possible paths to a key. Hence it's
1216            % not easily possible to replace an existing node with a new one,
1217            % as the insertion could happen in a subtree that is different
1218            % from the subtree of the old value.
1219            spatial_view ->
1220                BatchData = [
1221                    couch_set_view_updater_helper:encode_op(insert, K, V) ||
1222                        {K, V} <- AddKeyValuesBinaries],
1223                KeysToRemoveDict2 = KeysToRemoveDict
1224            end,
1225
1226            BatchData2 = dict:fold(
1227                fun(K, _V, BatchAcc) ->
1228                    Bin = couch_set_view_updater_helper:encode_op(remove, K),
1229                    [Bin | BatchAcc]
1230                end,
1231                BatchData, KeysToRemoveDict2),
1232
1233            ViewTmpFileInfo = dict:fetch(ViewId, TmpFiles),
1234            case ViewTmpFileInfo of
1235            #set_view_tmp_file_info{fd = nil} ->
1236                0 = ViewTmpFileInfo#set_view_tmp_file_info.size,
1237                ViewTmpFilePath = new_sort_file_name(WriterAcc),
1238                {ok, ViewTmpFileFd} = file2:open(
1239                    ViewTmpFilePath, [raw, append, binary]),
1240                ViewTmpFileSize = 0;
1241            #set_view_tmp_file_info{fd = ViewTmpFileFd,
1242                                    size = ViewTmpFileSize,
1243                                    name = ViewTmpFilePath} ->
1244                ok
1245            end,
1246            ok = file:write(ViewTmpFileFd, BatchData2),
1247            ViewTmpFileInfo2 = ViewTmpFileInfo#set_view_tmp_file_info{
1248                fd = ViewTmpFileFd,
1249                name = ViewTmpFilePath,
1250                size = ViewTmpFileSize + iolist_size(BatchData2)
1251            },
1252            dict:store(ViewId, ViewTmpFileInfo2, AccTmpFiles)
1253        end,
1254    TmpFiles, ViewKeyValues),
1255    WriterAcc#writer_acc{
1256        tmp_files = TmpFiles2
1257    }.
1258
1259
1260is_new_partition(PartId, #writer_acc{initial_seqs = InitialSeqs}) ->
1261    couch_util:get_value(PartId, InitialSeqs, 0) == 0.
1262
1263
1264% For incremental index updates.
1265maybe_update_btrees(WriterAcc0) ->
1266    #writer_acc{
1267        view_empty_kvs = ViewEmptyKVs,
1268        tmp_files = TmpFiles,
1269        group = Group0,
1270        final_batch = IsFinalBatch,
1271        owner = Owner,
1272        last_seqs = LastSeqs,
1273        part_versions = PartVersions,
1274        force_flush = ForceFlush
1275    } = WriterAcc0,
1276    IdTmpFileInfo = dict:fetch(ids_index, TmpFiles),
1277    ShouldFlushViews =
1278        lists:any(
1279            fun({#set_view{id_num = Id}, _}) ->
1280                ViewTmpFileInfo = dict:fetch(Id, TmpFiles),
1281                ViewTmpFileInfo#set_view_tmp_file_info.size >= ?INC_MAX_TMP_FILE_SIZE
1282            end, ViewEmptyKVs),
1283    ShouldFlush = IsFinalBatch orelse
1284        ForceFlush orelse
1285        ((IdTmpFileInfo#set_view_tmp_file_info.size >= ?INC_MAX_TMP_FILE_SIZE) andalso
1286        ShouldFlushViews),
1287    case ShouldFlush of
1288    false ->
1289        NewLastSeqs1 = LastSeqs,
1290        case erlang:get(updater_worker) of
1291        undefined ->
1292            WriterAcc = WriterAcc0;
1293        UpdaterWorker when is_reference(UpdaterWorker) ->
1294            receive
1295            {UpdaterWorker, UpGroup, UpStats, CompactFiles} ->
1296                send_log_compact_files(Owner, CompactFiles, ?set_seqs(UpGroup),
1297                    ?set_partition_versions(UpGroup)),
1298                erlang:erase(updater_worker),
1299                WriterAcc = check_if_compactor_started(
1300                    WriterAcc0#writer_acc{group = UpGroup, stats = UpStats})
1301            after 0 ->
1302                WriterAcc = WriterAcc0
1303            end
1304        end;
1305    true ->
1306        ok = close_tmp_fd(IdTmpFileInfo),
1307        ok = lists:foreach(
1308            fun(#set_view{id_num = Id}) ->
1309                ViewTmpFileInfo = dict:fetch(Id, TmpFiles),
1310                ok = close_tmp_fd(ViewTmpFileInfo)
1311            end,
1312            Group0#set_view_group.views),
1313        case erlang:erase(updater_worker) of
1314        undefined ->
1315            WriterAcc1 = WriterAcc0;
1316        UpdaterWorker when is_reference(UpdaterWorker) ->
1317            receive
1318            {UpdaterWorker, UpGroup2, UpStats2, CompactFiles2} ->
1319                send_log_compact_files(Owner, CompactFiles2, ?set_seqs(UpGroup2),
1320                    ?set_partition_versions(UpGroup2)),
1321                WriterAcc1 = check_if_compactor_started(
1322                    WriterAcc0#writer_acc{
1323                        group = UpGroup2,
1324                        stats = UpStats2
1325                    })
1326            end
1327        end,
1328
1329
1330        % MB-11472: There is no id sortfile present and hence this is the final batch
1331        % and nothing left to be updated to the btree
1332        case IdTmpFileInfo#set_view_tmp_file_info.name of
1333        nil ->
1334            WriterAcc = WriterAcc1;
1335        _ ->
1336            WriterAcc2 = check_if_compactor_started(WriterAcc1),
1337            NewUpdaterWorker = spawn_updater_worker(WriterAcc2, LastSeqs, PartVersions),
1338            erlang:put(updater_worker, NewUpdaterWorker),
1339
1340            TmpFiles2 = dict:map(
1341                fun(_, _) -> #set_view_tmp_file_info{} end, TmpFiles),
1342            WriterAcc = WriterAcc2#writer_acc{tmp_files = TmpFiles2}
1343        end,
1344        NewLastSeqs1 = orddict:new()
1345    end,
1346    #writer_acc{
1347        stats = NewStats0,
1348        group = NewGroup0
1349    } = WriterAcc,
1350    case IsFinalBatch of
1351    true ->
1352        case erlang:erase(updater_worker) of
1353        undefined ->
1354            NewGroup = NewGroup0,
1355            NewStats = NewStats0;
1356        UpdaterWorker2 when is_reference(UpdaterWorker2) ->
1357            receive
1358            {UpdaterWorker2, NewGroup, NewStats, CompactFiles3} ->
1359                send_log_compact_files(Owner, CompactFiles3, ?set_seqs(NewGroup),
1360                    ?set_partition_versions(NewGroup))
1361            end
1362        end,
1363        NewLastSeqs = orddict:new();
1364    false ->
1365        NewGroup = NewGroup0,
1366        NewStats = NewStats0,
1367        NewLastSeqs = NewLastSeqs1
1368    end,
1369    NewWriterAcc = WriterAcc#writer_acc{
1370        stats = NewStats,
1371        group = NewGroup,
1372        last_seqs = NewLastSeqs
1373    },
1374    NewWriterAcc.
1375
1376
1377send_log_compact_files(_Owner, [], _Seqs, _PartVersions) ->
1378    ok;
1379send_log_compact_files(Owner, Files, Seqs, PartVersions) ->
1380    Init = case erlang:erase(new_compactor) of
1381    true ->
1382        true;
1383    undefined ->
1384        false
1385    end,
1386    ok = gen_server:cast(Owner, {compact_log_files, Files, Seqs, PartVersions, Init}).
1387
1388
1389-spec spawn_updater_worker(#writer_acc{}, partition_seqs(),
1390                           partition_versions()) -> reference().
1391spawn_updater_worker(WriterAcc, PartIdSeqs, PartVersions) ->
1392    Parent = self(),
1393    Ref = make_ref(),
1394    #writer_acc{
1395        group = Group,
1396        parent = UpdaterPid,
1397        max_seqs = MaxSeqs
1398    } = WriterAcc,
1399    % Wait for main updater process to ack
1400    UpdaterPid ! {native_updater_start, self()},
1401    receive
1402    {ok, native_updater_start} ->
1403        ok
1404    end,
1405    Pid = spawn_link(fun() ->
1406        case ?set_cbitmask(Group) of
1407        0 ->
1408            CleanupStart = 0;
1409        _ ->
1410            CleanupStart = os:timestamp()
1411        end,
1412        {ok, NewGroup0, CleanupCount, NewStats, NewCompactFiles} = update_btrees(WriterAcc),
1413        case ?set_cbitmask(Group) of
1414        0 ->
1415            CleanupTime = 0.0;
1416        _ ->
1417            CleanupTime = timer:now_diff(os:timestamp(), CleanupStart) / 1000000,
1418            #set_view_group{
1419                set_name = SetName,
1420                name = DDocId,
1421                type = GroupType
1422            } = Group,
1423            ?LOG_INFO("Updater for set view `~s`, ~s group `~s`, performed cleanup "
1424                      "of ~p key/value pairs in ~.3f seconds",
1425                      [SetName, GroupType, DDocId, CleanupCount, CleanupTime])
1426        end,
1427        NewSeqs = update_seqs(PartIdSeqs, ?set_seqs(Group)),
1428        NewPartVersions = update_versions(PartVersions, ?set_partition_versions(Group)),
1429        Header = NewGroup0#set_view_group.index_header,
1430        NewHeader = Header#set_view_index_header{
1431            seqs = NewSeqs,
1432            partition_versions = NewPartVersions
1433        },
1434        NewGroup = NewGroup0#set_view_group{
1435            index_header = NewHeader
1436        },
1437        NewGroup2 = update_transferred_replicas(NewGroup, MaxSeqs, PartIdSeqs),
1438        NumChanges = count_seqs_done(Group, NewSeqs),
1439        NewStats2 = NewStats#set_view_updater_stats{
1440           seqs = NewStats#set_view_updater_stats.seqs + NumChanges,
1441           cleanup_time = NewStats#set_view_updater_stats.seqs + CleanupTime,
1442           cleanup_kv_count = NewStats#set_view_updater_stats.cleanup_kv_count + CleanupCount
1443        },
1444        Parent ! {Ref, NewGroup2, NewStats2, NewCompactFiles}
1445    end),
1446    UpdaterPid ! {native_updater_pid, Pid},
1447    Ref.
1448
1449% Update id btree and view btrees with current batch of changes
1450update_btrees(WriterAcc) ->
1451    #writer_acc{
1452        stats = Stats,
1453        group = Group0,
1454        tmp_dir = TmpDir,
1455        tmp_files = TmpFiles,
1456        compactor_running = CompactorRunning,
1457        max_insert_batch_size = MaxBatchSize
1458    } = WriterAcc,
1459
1460    % Prepare list of operation logs for each btree
1461    #set_view_tmp_file_info{name = IdFile} = dict:fetch(ids_index, TmpFiles),
1462    ViewFiles = lists:map(
1463        fun(#set_view{id_num = Id}) ->
1464            #set_view_tmp_file_info{
1465                name = ViewFile
1466            } = dict:fetch(Id, TmpFiles),
1467            ViewFile
1468        end, Group0#set_view_group.views),
1469    % `LogFiles` is supplied to the native updater. For spatial views only the
1470    % ID b-tree is updated.
1471    LogFiles = case Group0#set_view_group.mod of
1472    mapreduce_view ->
1473        [IdFile | ViewFiles];
1474    spatial_view ->
1475        [IdFile]
1476    end,
1477
1478    % Remove spatial views from group
1479    % The native updater can currently handle mapreduce views only, but it
1480    % handles the ID b-tree of the spatial view
1481    Group = couch_set_view_util:remove_group_views(Group0, spatial_view),
1482
1483    {ok, NewGroup0, Stats2} = couch_set_view_updater_helper:update_btrees(
1484        Group, TmpDir, LogFiles, MaxBatchSize, false),
1485    {IdsInserted, IdsDeleted, KVsInserted, KVsDeleted, CleanupCount} = Stats2,
1486
1487    % Add back spatial views
1488    NewGroup = couch_set_view_util:update_group_views(
1489        NewGroup0, Group0, spatial_view),
1490
1491    % The native update for the Id b-tree was run, now it's time to run the
1492    % Erlang updater for the spatial views
1493    NewGroup2 = case NewGroup#set_view_group.mod of
1494    mapreduce_view ->
1495        NewGroup;
1496    spatial_view = Mod ->
1497        ok = couch_file:refresh_eof(NewGroup#set_view_group.fd),
1498        Views = Mod:update_spatial(NewGroup#set_view_group.views, ViewFiles,
1499            MaxBatchSize),
1500        NewGroup#set_view_group{
1501            views = Views,
1502            index_header = (NewGroup#set_view_group.index_header)#set_view_index_header{
1503                view_states = [Mod:get_state(V#set_view.indexer) || V <- Views]
1504            }
1505        }
1506    end,
1507
1508    NewStats = Stats#set_view_updater_stats{
1509     inserted_ids = Stats#set_view_updater_stats.inserted_ids + IdsInserted,
1510     deleted_ids = Stats#set_view_updater_stats.deleted_ids + IdsDeleted,
1511     inserted_kvs = Stats#set_view_updater_stats.inserted_kvs + KVsInserted,
1512     deleted_kvs = Stats#set_view_updater_stats.deleted_kvs + KVsDeleted
1513    },
1514
1515    % Remove files if compactor is not running
1516    % Otherwise send them to compactor to apply deltas
1517    CompactFiles = lists:foldr(
1518        fun(SortedFile, AccCompactFiles) ->
1519            case CompactorRunning of
1520            true ->
1521                case filename:extension(SortedFile) of
1522                ".compact" ->
1523                     [SortedFile | AccCompactFiles];
1524                _ ->
1525                    SortedFile2 = new_sort_file_name(TmpDir, true),
1526                    ok = file2:rename(SortedFile, SortedFile2),
1527                    [SortedFile2 | AccCompactFiles]
1528                end;
1529            false ->
1530                ok = file2:delete(SortedFile),
1531                AccCompactFiles
1532            end
1533        end, [], [IdFile | ViewFiles]),
1534    {ok, NewGroup2, CleanupCount, NewStats, CompactFiles}.
1535
1536
1537update_seqs(PartIdSeqs, Seqs) ->
1538    orddict:fold(
1539        fun(PartId, NewSeq, Acc) ->
1540            OldSeq = couch_util:get_value(PartId, Acc, 0),
1541            case NewSeq > OldSeq of
1542            true ->
1543                ok;
1544            false ->
1545                exit({error, <<"New seq smaller or equal than old seq.">>, PartId, OldSeq, NewSeq})
1546            end,
1547            orddict:store(PartId, NewSeq, Acc)
1548        end,
1549        Seqs, PartIdSeqs).
1550
1551update_versions(PartVersions, AllPartVersions) ->
1552    lists:ukeymerge(1, PartVersions, AllPartVersions).
1553
1554
1555update_task(NumChanges) ->
1556    [Changes, Total] = couch_task_status:get([changes_done, total_changes]),
1557    Changes2 = Changes + NumChanges,
1558    Total2 = erlang:max(Total, Changes2),
1559    Progress = (Changes2 * 100) div Total2,
1560    couch_task_status:update([
1561        {progress, Progress},
1562        {changes_done, Changes2},
1563        {total_changes, Total2}
1564    ]).
1565
1566
1567checkpoint(#writer_acc{owner = Owner, parent = Parent, group = Group} = Acc) ->
1568    #set_view_group{
1569        set_name = SetName,
1570        name = DDocId,
1571        type = Type
1572    } = Group,
1573    ?LOG_INFO("Updater checkpointing set view `~s` update for ~s group `~s`",
1574              [SetName, Type, DDocId]),
1575    NewGroup = maybe_fix_group(Group),
1576    ok = couch_file:refresh_eof(NewGroup#set_view_group.fd),
1577    Owner ! {partial_update, Parent, self(), NewGroup},
1578    receive
1579    update_processed ->
1580        ok;
1581    stop ->
1582        exit(shutdown)
1583    end,
1584    Acc#writer_acc{group = NewGroup}.
1585
1586
1587maybe_fix_group(#set_view_group{index_header = Header} = Group) ->
1588    receive
1589    {new_passive_partitions, Parts} ->
1590        Bitmask = couch_set_view_util:build_bitmask(Parts),
1591        {Seqs, PartVersions} = couch_set_view_util:fix_partitions(Group, Parts),
1592        Group#set_view_group{
1593            index_header = Header#set_view_index_header{
1594                seqs = Seqs,
1595                pbitmask = ?set_pbitmask(Group) bor Bitmask,
1596                partition_versions = PartVersions
1597            }
1598        }
1599    after 0 ->
1600        Group
1601    end.
1602
1603
1604check_if_compactor_started(#writer_acc{group = Group0} = Acc) ->
1605    receive
1606    {compactor_started, Pid} ->
1607        erlang:put(new_compactor, true),
1608        Group = maybe_fix_group(Group0),
1609        Pid ! {compactor_started_ack, self(), Group},
1610        Acc#writer_acc{compactor_running = true, group = Group}
1611    after 0 ->
1612        Acc
1613    end.
1614
1615
1616init_tmp_files(WriterAcc) ->
1617    #writer_acc{
1618        group = Group, initial_build = Init, tmp_dir = TmpDir
1619    } = WriterAcc,
1620    case WriterAcc#writer_acc.compactor_running of
1621    true ->
1622        ok = couch_set_view_util:delete_sort_files(TmpDir, updater);
1623    false ->
1624        ok = couch_set_view_util:delete_sort_files(TmpDir, all)
1625    end,
1626    Ids = [ids_index | [V#set_view.id_num || V <- Group#set_view_group.views]],
1627    Files = case Init of
1628    true ->
1629        [begin
1630             FileName = new_sort_file_name(WriterAcc),
1631             {ok, Fd} = file2:open(FileName, [raw, append, binary]),
1632             {Id, #set_view_tmp_file_info{fd = Fd, name = FileName}}
1633         end || Id <- Ids];
1634    false ->
1635         [{Id, #set_view_tmp_file_info{}} || Id <- Ids]
1636    end,
1637    WriterAcc#writer_acc{tmp_files = dict:from_list(Files)}.
1638
1639
1640new_sort_file_name(#writer_acc{tmp_dir = TmpDir, compactor_running = Cr}) ->
1641    new_sort_file_name(TmpDir, Cr).
1642
1643new_sort_file_name(TmpDir, true) ->
1644    couch_set_view_util:new_sort_file_path(TmpDir, compactor);
1645new_sort_file_name(TmpDir, false) ->
1646    couch_set_view_util:new_sort_file_path(TmpDir, updater).
1647
1648
1649make_back_index_key(DocId, PartId) ->
1650    <<PartId:16, DocId/binary>>.
1651
1652
1653count_seqs_done(Group, NewSeqs) ->
1654    % NewSeqs might have new passive partitions that Group's seqs doesn't
1655    % have yet (will get them after a checkpoint period).
1656    lists:foldl(
1657        fun({PartId, SeqDone}, Acc) ->
1658            SeqBefore = couch_util:get_value(PartId, ?set_seqs(Group), 0),
1659            Acc + (SeqDone - SeqBefore)
1660        end,
1661        0, NewSeqs).
1662
1663
1664close_tmp_fd(#set_view_tmp_file_info{fd = nil}) ->
1665    ok;
1666close_tmp_fd(#set_view_tmp_file_info{fd = Fd}) ->
1667    ok = file:close(Fd).
1668
1669
1670% DCP introduces the concept of snapshots, where a document mutation is only
1671% guaranteed to be unique within a single snapshot. But the flusher expects
1672% unique mutations within the full batch. Merge multiple snapshots (if there
1673% are any) into a single one. The latest mutation wins.
1674merge_snapshots(KVs) ->
1675    merge_snapshots(KVs, false, []).
1676
1677merge_snapshots([], true, Acc) ->
1678    {true, Acc};
1679merge_snapshots([], false, Acc) ->
1680    % The order of the KVs doesn't really matter, but having them sorted the
1681    % same way will make life easier when debugging
1682    {false, lists:reverse(Acc)};
1683merge_snapshots([snapshot_marker | KVs], _MultipleSnapshots, Acc) ->
1684    merge_snapshots(KVs, true, Acc);
1685merge_snapshots([{part_versions, _} = PartVersions | KVs], MultipleSnapshots, Acc) ->
1686    merge_snapshots(KVs, MultipleSnapshots, [PartVersions | Acc]);
1687merge_snapshots([KV | KVs], true, Acc0) ->
1688    {_Seq, DocId, _PartId, _QueryResults} = KV,
1689    Acc = lists:keystore(DocId, 2, Acc0, KV),
1690    merge_snapshots(KVs, true, Acc);
1691merge_snapshots([KV | KVs], false, Acc) ->
1692    merge_snapshots(KVs, false, [KV | Acc]).
1693