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    case Doc#dcp_doc.deleted of
663    true when InitialBuild ->
664        Entry = nil;
665    true ->
666        Entry = Doc;
667    false ->
668        #set_view_group{
669           set_name = SetName,
670           name = DDocId,
671           type = GroupType
672        } = Group,
673        case couch_util:validate_utf8(Doc#dcp_doc.id) of
674        true ->
675            case (MaxDocSize > 0) andalso
676                (iolist_size(Doc#dcp_doc.body) > MaxDocSize) of
677            true ->
678                ?LOG_MAPREDUCE_ERROR("Bucket `~s`, ~s group `~s`, skipping "
679                    "document with ID `~s`: too large body (~p bytes)",
680                    [SetName, GroupType, DDocId,
681                     ?b2l(Doc#dcp_doc.id), iolist_size(Doc#dcp_doc.body)]),
682                Entry = Doc#dcp_doc{deleted = true};
683            false ->
684                Entry = Doc
685            end;
686        false ->
687            % If the id isn't utf8 (memcached allows it), then log an error
688            % message and skip the doc. Send it through the queue anyway
689            % so we record the high seq num in case there are a bunch of
690            % these at the end, we want to keep track of the high seq and
691            % not reprocess again.
692            ?LOG_MAPREDUCE_ERROR("Bucket `~s`, ~s group `~s`, skipping "
693                "document with non-utf8 id. Doc id bytes: ~w",
694                [SetName, GroupType, DDocId, ?b2l(Doc#dcp_doc.id)]),
695            Entry = Doc#dcp_doc{deleted = true}
696        end
697    end,
698    case Entry of
699    nil ->
700        ok;
701    _ ->
702        couch_work_queue:queue(MapQueue, Entry),
703        update_task(1)
704    end.
705
706-spec accumulate_xattr(binary(), binary(), non_neg_integer(), non_neg_integer()) ->
707    {binary(), binary()}.
708accumulate_xattr(Data, Acc, XATTRSize, AccSum) when AccSum =:= XATTRSize ->
709    {Data, <<Acc/binary, "}">>};
710accumulate_xattr(Body, Acc, XATTRSize, AccSum) ->
711    <<DataSize:32, Rest/binary>> = Body,
712    AccSum2 = AccSum + DataSize + 4,
713    <<Data0:DataSize/binary, Rest2/binary>> = Rest,
714    % Remove last zero value from  XATTR
715    Data = binary:part(Data0, 0, DataSize-1),
716    % Jsonify key and value
717    Data2 = case AccSum2 of
718    XATTRSize ->
719        <<"\"", Data/binary>>;
720    _ ->
721        <<"\"", Data/binary, ",">>
722    end,
723    % Replace zero byte after key with colon
724    Xattr = binary:replace(Data2, <<0>>, <<"\":">>),
725    accumulate_xattr(Rest2, <<Acc/binary, Xattr/binary>>, XATTRSize, AccSum2).
726
727do_maps(Group, MapQueue, WriteQueue) ->
728    #set_view_group{
729        set_name = SetName,
730        name = DDocId,
731        type = Type,
732        mod = Mod
733    } = Group,
734    case couch_work_queue:dequeue(MapQueue) of
735    closed ->
736        couch_work_queue:close(WriteQueue);
737    {ok, Queue, _QueueSize} ->
738        ViewCount = length(Group#set_view_group.views),
739        {Items, _} = lists:foldl(
740            fun(#dcp_doc{deleted = true} = DcpDoc, {Acc, Size}) ->
741                #dcp_doc{
742                    id = Id,
743                    partition = PartId,
744                    seq = Seq
745                } = DcpDoc,
746                Item = {Seq, Id, PartId, []},
747                {[Item | Acc], Size};
748            (#dcp_doc{deleted = false} = DcpDoc, {Acc0, Size0}) ->
749                % When there are a lot of emits per document the memory can
750                % grow almost indefinitely as the queue size is only limited
751                % by the number of documents and not their emits.
752                % In case the accumulator grows huge, queue the items early
753                % into the writer queue. Only take emits into account, the
754                % other cases in this `foldl` won't ever have an significant
755                % size.
756                {Acc, Size} = case Size0 > ?QUEUE_ACC_BATCH_SIZE of
757                true ->
758                    couch_work_queue:queue(WriteQueue, lists:reverse(Acc0)),
759                    {[], 0};
760                false ->
761                    {Acc0, Size0}
762                end,
763                #dcp_doc{
764                    id = Id,
765                    body = Body,
766                    partition = PartId,
767                    rev_seq = RevSeq,
768                    seq = Seq,
769                    cas = Cas,
770                    expiration = Expiration,
771                    flags = Flags,
772                    data_type = DcpDataType
773                } = DcpDoc,
774                {DataType, DocBody, XATTRs} = case DcpDataType of
775                ?DCP_DATA_TYPE_RAW ->
776                    {DocBody2, XATTRs2} = accumulate_xattr(Body, <<"\"xattrs\":{">>, 0, 0),
777                    {?CONTENT_META_NON_JSON_MODE, DocBody2, XATTRs2};
778                ?DCP_DATA_TYPE_JSON ->
779                    {DocBody3, XATTRs3} = accumulate_xattr(Body, <<"\"xattrs\":{">>, 0, 0),
780                    {?CONTENT_META_JSON, DocBody3, XATTRs3};
781                ?DCP_DATA_TYPE_BINARY_XATTR ->
782                    <<XATTRSize:32, Rest/binary>> = Body,
783                    {DocBody4, XATTRs4} = accumulate_xattr(Rest, <<"\"xattrs\":{">>, XATTRSize, 0),
784                    {?CONTENT_META_NON_JSON_MODE, DocBody4, XATTRs4};
785                ?DCP_DATA_TYPE_JSON_XATTR ->
786                    <<XATTRSize:32, Rest/binary>> = Body,
787                    {DocBody5, XATTRs5} = accumulate_xattr(Rest, <<"\"xattrs\":{">>, XATTRSize, 0),
788                    {?CONTENT_META_JSON, DocBody5, XATTRs5}
789                end,
790                Doc = #doc{
791                    id = Id,
792                    rev = {RevSeq, <<Cas:64, Expiration:32, Flags:32>>},
793                    body = DocBody,
794                    content_meta = DataType,
795                    deleted = false
796                },
797                try
798                    {ok, Result, LogList} = couch_set_view_mapreduce:map(
799                        Doc, XATTRs, PartId, Seq, Group),
800                    {Result2, _} = lists:foldr(
801                        fun({error, Reason}, {AccRes, Pos}) ->
802                            ErrorMsg = "Bucket `~s`, ~s group `~s`, error mapping"
803                                    " document `~s` for view `~s`: ~s",
804                            ViewName = Mod:view_name(Group, Pos),
805                            Args = [SetName, Type, DDocId, Id, ViewName,
806                                    couch_util:to_binary(Reason)],
807                            ?LOG_MAPREDUCE_ERROR(ErrorMsg, Args),
808                            {[[] | AccRes], Pos - 1};
809                        (KVs, {AccRes, Pos}) ->
810                            {[KVs | AccRes], Pos - 1}
811                        end,
812                        {[], ViewCount}, Result),
813                    lists:foreach(
814                        fun(Msg) ->
815                            DebugMsg = "Bucket `~s`, ~s group `~s`, map function"
816                                " log for document `~s`: ~s",
817                            Args = [SetName, Type, DDocId, Id, binary_to_list(Msg)],
818                            ?LOG_MAPREDUCE_ERROR(DebugMsg, Args)
819                        end, LogList),
820                    Item = {Seq, Id, PartId, Result2},
821                    {[Item | Acc], Size + erlang:external_size(Result2)}
822                catch _:{error, Reason} ->
823                    ErrorMsg = "Bucket `~s`, ~s group `~s`, error mapping document `~s`: ~s",
824                    Args = [SetName, Type, DDocId, Id, couch_util:to_binary(Reason)],
825                    ?LOG_MAPREDUCE_ERROR(ErrorMsg, Args),
826                    {[{Seq, Id, PartId, []} | Acc], Size}
827                end;
828            (snapshot_marker, {Acc, Size}) ->
829                {[snapshot_marker | Acc], Size};
830            ({part_versions, _} = PartVersions, {Acc, Size}) ->
831                {[PartVersions | Acc], Size}
832            end,
833            {[], 0}, Queue),
834        ok = couch_work_queue:queue(WriteQueue, lists:reverse(Items)),
835        do_maps(Group, MapQueue, WriteQueue)
836    end.
837
838
839do_writes(Acc) ->
840    #writer_acc{
841        kvs = Kvs,
842        kvs_size = KvsSize,
843        write_queue = WriteQueue,
844        throttle = Throttle
845    } = Acc,
846    ok = timer:sleep(Throttle),
847    case couch_work_queue:dequeue(WriteQueue) of
848    closed ->
849        flush_writes(Acc#writer_acc{final_batch = true});
850    {ok, Queue0, QueueSize} ->
851        Queue = lists:flatten(Queue0),
852        Kvs2 = Kvs ++ Queue,
853        KvsSize2 = KvsSize + QueueSize,
854
855        Acc2 = Acc#writer_acc{
856            kvs = Kvs2,
857            kvs_size = KvsSize2
858        },
859        case should_flush_writes(Acc2) of
860        true ->
861            Acc3 = flush_writes(Acc2),
862            Acc4 = Acc3#writer_acc{kvs = [], kvs_size = 0};
863        false ->
864            Acc4 = Acc2
865        end,
866        do_writes(Acc4)
867    end.
868
869should_flush_writes(Acc) ->
870    #writer_acc{
871        view_empty_kvs = ViewEmptyKvs,
872        kvs_size = KvsSize
873    } = Acc,
874    KvsSize >= (?MIN_BATCH_SIZE_PER_VIEW * length(ViewEmptyKvs)).
875
876
877flush_writes(#writer_acc{kvs = [], initial_build = false} = Acc) ->
878    Acc2 = maybe_update_btrees(Acc),
879    checkpoint(Acc2);
880
881flush_writes(#writer_acc{initial_build = false} = Acc0) ->
882    #writer_acc{
883        kvs = Kvs,
884        view_empty_kvs = ViewEmptyKVs,
885        group = Group,
886        parent = Parent,
887        owner = Owner,
888        final_batch = IsFinalBatch,
889        part_versions = PartVersions
890    } = Acc0,
891    Mod = Group#set_view_group.mod,
892    % Only incremental updates can contain multiple snapshots
893    {MultipleSnapshots, Kvs2} = merge_snapshots(Kvs),
894    Acc1 = case MultipleSnapshots of
895    true ->
896        Acc2 = maybe_update_btrees(Acc0#writer_acc{force_flush = true}),
897        checkpoint(Acc2);
898    false ->
899        Acc0
900    end,
901    #writer_acc{last_seqs = LastSeqs} = Acc1,
902    {ViewKVs, DocIdViewIdKeys, NewLastSeqs, NewPartVersions} =
903        process_map_results(Mod, Kvs2, ViewEmptyKVs, LastSeqs, PartVersions),
904    Acc3 = Acc1#writer_acc{last_seqs = NewLastSeqs, part_versions = NewPartVersions},
905    Acc4 = write_to_tmp_batch_files(ViewKVs, DocIdViewIdKeys, Acc3),
906    #writer_acc{group = NewGroup} = Acc4,
907    case ?set_seqs(NewGroup) =/= ?set_seqs(Group) of
908    true ->
909        Acc5 = checkpoint(Acc4),
910        case (Acc4#writer_acc.state =:= updating_active) andalso
911            lists:any(fun({PartId, _}) ->
912                ((1 bsl PartId) band ?set_pbitmask(Group) =/= 0)
913            end, NewLastSeqs) of
914        true ->
915            notify_owner(Owner, {state, updating_passive}, Parent),
916            Acc5#writer_acc{state = updating_passive};
917        false ->
918            Acc5
919        end;
920    false ->
921        case IsFinalBatch of
922        true ->
923            checkpoint(Acc4);
924        false ->
925            Acc4
926        end
927    end;
928
929flush_writes(#writer_acc{initial_build = true} = WriterAcc) ->
930    #writer_acc{
931        kvs = Kvs,
932        view_empty_kvs = ViewEmptyKVs,
933        tmp_files = TmpFiles,
934        tmp_dir = TmpDir,
935        group = Group,
936        final_batch = IsFinalBatch,
937        max_seqs = MaxSeqs,
938        part_versions = PartVersions,
939        stats = Stats
940    } = WriterAcc,
941    #set_view_group{
942        set_name = SetName,
943        type = Type,
944        name = DDocId,
945        mod = Mod
946    } = Group,
947    {ViewKVs, DocIdViewIdKeys, MaxSeqs2, PartVersions2} = process_map_results(
948        Mod, Kvs, ViewEmptyKVs, MaxSeqs, PartVersions),
949
950    IdRecords = lists:foldr(
951        fun({_DocId, {_PartId, []}}, Acc) ->
952                Acc;
953            (Kv, Acc) ->
954                [{KeyBin, ValBin}] = Mod:convert_back_index_kvs_to_binary([Kv], []),
955                KvBin = [<<(byte_size(KeyBin)):16>>, KeyBin, ValBin],
956                [[<<(iolist_size(KvBin)):32/native>>, KvBin] | Acc]
957        end,
958        [], DocIdViewIdKeys),
959    #set_view_tmp_file_info{fd = IdFd} = dict:fetch(ids_index, TmpFiles),
960    ok = file:write(IdFd, IdRecords),
961
962    {InsertKVCount, TmpFiles2} = Mod:write_kvs(Group, TmpFiles, ViewKVs),
963
964    Stats2 = Stats#set_view_updater_stats{
965        inserted_kvs = Stats#set_view_updater_stats.inserted_kvs + InsertKVCount,
966        inserted_ids = Stats#set_view_updater_stats.inserted_ids + length(DocIdViewIdKeys)
967    },
968    case IsFinalBatch of
969    false ->
970        WriterAcc#writer_acc{
971            max_seqs = MaxSeqs2,
972            stats = Stats2,
973            tmp_files = TmpFiles2
974        };
975    true ->
976        ?LOG_INFO("Updater for set view `~s`, ~s group `~s`, starting btree "
977                  "build phase" , [SetName, Type, DDocId]),
978        {Group2, BuildFd} = Mod:finish_build(Group, TmpFiles2, TmpDir),
979        WriterAcc#writer_acc{
980            tmp_files = dict:store(build_file, BuildFd, TmpFiles2),
981            max_seqs = MaxSeqs2,
982            part_versions = PartVersions2,
983            stats = Stats2,
984            group = Group2
985        }
986    end.
987
988
989process_map_results(Mod, Kvs, ViewEmptyKVs, PartSeqs, PartVersions) ->
990    lists:foldl(
991        fun({Seq, DocId, PartId, []}, {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions}) ->
992            PartIdSeqs2 = update_part_seq(Seq, PartId, PartIdSeqs),
993            {ViewKVsAcc, [{DocId, {PartId, []}} | DocIdViewIdKeysAcc], PartIdSeqs2, PartIdVersions};
994        ({Seq, DocId, PartId, QueryResults}, {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions}) ->
995            {NewViewKVs, NewViewIdKeys} = Mod:view_insert_doc_query_results(
996                    DocId, PartId, QueryResults, ViewKVsAcc, [], []),
997            PartIdSeqs2 = update_part_seq(Seq, PartId, PartIdSeqs),
998            {NewViewKVs, [{DocId, {PartId, NewViewIdKeys}} | DocIdViewIdKeysAcc], PartIdSeqs2, PartIdVersions};
999        (snapshot_marker, _Acc) ->
1000            throw({error,
1001                <<"The multiple snapshots should have been merged, "
1002                  "but theu weren't">>});
1003        ({part_versions, {PartId, NewVersions}}, {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions}) ->
1004            PartIdVersions2 = update_part_versions(NewVersions, PartId, PartIdVersions),
1005            {ViewKVsAcc, DocIdViewIdKeysAcc, PartIdSeqs, PartIdVersions2}
1006        end,
1007        {ViewEmptyKVs, [], PartSeqs, PartVersions}, Kvs).
1008
1009
1010-spec update_transferred_replicas(#set_view_group{},
1011                                  partition_seqs(),
1012                                  partition_seqs()) -> #set_view_group{}.
1013update_transferred_replicas(Group, _MaxSeqs, _PartIdSeqs) when ?set_replicas_on_transfer(Group) =:= [] ->
1014    Group;
1015update_transferred_replicas(Group, MaxSeqs, PartIdSeqs) ->
1016    #set_view_group{index_header = Header} = Group,
1017    RepsTransferred = lists:foldl(
1018        fun({PartId, Seq}, A) ->
1019            case lists:member(PartId, ?set_replicas_on_transfer(Group))
1020                andalso (Seq >= couch_set_view_util:get_part_seq(PartId, MaxSeqs)) of
1021            true ->
1022                ordsets:add_element(PartId, A);
1023            false ->
1024                A
1025            end
1026        end,
1027        ordsets:new(), PartIdSeqs),
1028    ReplicasOnTransfer2 = ordsets:subtract(?set_replicas_on_transfer(Group), RepsTransferred),
1029    {Abitmask2, Pbitmask2} = lists:foldl(
1030        fun(Id, {A, P}) ->
1031            Mask = 1 bsl Id,
1032            Mask = ?set_pbitmask(Group) band Mask,
1033            0 = ?set_abitmask(Group) band Mask,
1034            {A bor Mask, P bxor Mask}
1035        end,
1036        {?set_abitmask(Group), ?set_pbitmask(Group)},
1037        RepsTransferred),
1038    Group#set_view_group{
1039        index_header = Header#set_view_index_header{
1040            abitmask = Abitmask2,
1041            pbitmask = Pbitmask2,
1042            replicas_on_transfer = ReplicasOnTransfer2
1043        }
1044    }.
1045
1046
1047-spec update_part_seq(update_seq(), partition_id(), partition_seqs()) -> partition_seqs().
1048update_part_seq(Seq, PartId, Acc) ->
1049    case couch_set_view_util:find_part_seq(PartId, Acc) of
1050    {ok, Max} when Max >= Seq ->
1051        Acc;
1052    _ ->
1053        orddict:store(PartId, Seq, Acc)
1054    end.
1055
1056
1057-spec update_part_versions(partition_version(), partition_id(), partition_versions()) ->
1058    partition_versions().
1059update_part_versions(NewVersions, PartId, PartVersions) ->
1060    orddict:store(PartId, NewVersions, PartVersions).
1061
1062
1063% Incremental updates.
1064write_to_tmp_batch_files(ViewKeyValuesToAdd, DocIdViewIdKeys, WriterAcc) ->
1065    #writer_acc{
1066        tmp_files = TmpFiles,
1067        group = #set_view_group{
1068            id_btree = IdBtree,
1069            mod = Mod
1070        }
1071    } = WriterAcc,
1072
1073    {AddDocIdViewIdKeys0, RemoveDocIds, LookupDocIds} = lists:foldr(
1074        fun({DocId, {PartId, [] = _ViewIdKeys}}, {A, B, C}) ->
1075                BackKey = make_back_index_key(DocId, PartId),
1076                case is_new_partition(PartId, WriterAcc) of
1077                true ->
1078                    {A, [BackKey | B], C};
1079                false ->
1080                    {A, [BackKey | B], [BackKey | C]}
1081                end;
1082            ({DocId, {PartId, _ViewIdKeys}} = KvPairs, {A, B, C}) ->
1083                BackKey = make_back_index_key(DocId, PartId),
1084                case is_new_partition(PartId, WriterAcc) of
1085                true ->
1086                    {[KvPairs | A], B, C};
1087                false ->
1088                    {[KvPairs | A], B, [BackKey | C]}
1089                end
1090        end,
1091        {[], [], []}, DocIdViewIdKeys),
1092
1093    AddDocIdViewIdKeys = Mod:convert_back_index_kvs_to_binary(
1094        AddDocIdViewIdKeys0, []),
1095
1096    IdsData1 = lists:map(
1097        fun(K) -> couch_set_view_updater_helper:encode_op(remove, K) end,
1098        RemoveDocIds),
1099
1100    IdsData2 = lists:foldl(
1101        fun({K, V}, Acc) ->
1102            Bin = couch_set_view_updater_helper:encode_op(insert, K, V),
1103            [Bin | Acc]
1104        end,
1105        IdsData1,
1106        AddDocIdViewIdKeys),
1107
1108    IdTmpFileInfo = dict:fetch(ids_index, TmpFiles),
1109    case IdTmpFileInfo of
1110    #set_view_tmp_file_info{fd = nil} ->
1111        0 = IdTmpFileInfo#set_view_tmp_file_info.size,
1112        IdTmpFilePath = new_sort_file_name(WriterAcc),
1113        {ok, IdTmpFileFd} = file2:open(IdTmpFilePath, [raw, append, binary]),
1114        IdTmpFileSize = 0;
1115    #set_view_tmp_file_info{
1116            fd = IdTmpFileFd, name = IdTmpFilePath, size = IdTmpFileSize} ->
1117        ok
1118    end,
1119
1120    ok = file:write(IdTmpFileFd, IdsData2),
1121
1122    IdTmpFileInfo2 = IdTmpFileInfo#set_view_tmp_file_info{
1123        fd = IdTmpFileFd,
1124        name = IdTmpFilePath,
1125        size = IdTmpFileSize + iolist_size(IdsData2)
1126    },
1127    TmpFiles2 = dict:store(ids_index, IdTmpFileInfo2, TmpFiles),
1128
1129    case LookupDocIds of
1130    [] ->
1131        LookupResults = [];
1132    _ ->
1133        {ok, LookupResults, IdBtree} =
1134            couch_btree:query_modify(IdBtree, LookupDocIds, [], [])
1135    end,
1136    KeysToRemoveByView = lists:foldl(
1137        fun(LookupResult, KeysToRemoveByViewAcc) ->
1138            case LookupResult of
1139            {ok, {<<_Part:16, DocId/binary>>, <<_Part:16, ViewIdKeys/binary>>}} ->
1140                lists:foldl(
1141                    fun({ViewId, Keys}, KeysToRemoveByViewAcc2) ->
1142                        RemoveKeysDict = lists:foldl(
1143                            fun(Key, RemoveKeysDictAcc) ->
1144                                EncodedKey = Mod:encode_key_docid(Key, DocId),
1145                                dict:store(EncodedKey, nil, RemoveKeysDictAcc)
1146                            end,
1147                        couch_util:dict_find(ViewId, KeysToRemoveByViewAcc2, dict:new()), Keys),
1148                        dict:store(ViewId, RemoveKeysDict, KeysToRemoveByViewAcc2)
1149                    end,
1150                    KeysToRemoveByViewAcc, couch_set_view_util:parse_view_id_keys(ViewIdKeys));
1151            {not_found, _} ->
1152                KeysToRemoveByViewAcc
1153            end
1154        end,
1155        dict:new(), LookupResults),
1156
1157    WriterAcc2 = update_tmp_files(
1158        Mod, WriterAcc#writer_acc{tmp_files = TmpFiles2}, ViewKeyValuesToAdd,
1159        KeysToRemoveByView),
1160    maybe_update_btrees(WriterAcc2).
1161
1162
1163% Update the temporary files with the key-values from the indexer. Return
1164% the updated writer accumulator.
1165-spec update_tmp_files(atom(), #writer_acc{},
1166                       [{#set_view{}, [set_view_key_value()]}],
1167                       dict:dict(non_neg_integer(), dict:dict(binary(), nil)))
1168                      -> #writer_acc{}.
1169update_tmp_files(Mod, WriterAcc, ViewKeyValues, KeysToRemoveByView) ->
1170    #writer_acc{
1171       group = Group,
1172       tmp_files = TmpFiles
1173    } = WriterAcc,
1174    TmpFiles2 = lists:foldl(
1175        fun({#set_view{id_num = ViewId}, AddKeyValues}, AccTmpFiles) ->
1176            AddKeyValuesBinaries = Mod:convert_primary_index_kvs_to_binary(
1177                AddKeyValues, Group, []),
1178            KeysToRemoveDict = couch_util:dict_find(
1179                ViewId, KeysToRemoveByView, dict:new()),
1180
1181            case Mod of
1182            % The b-tree replaces nodes with the same key, hence we don't
1183            % need to delete a node that gets updated anyway
1184            mapreduce_view ->
1185                {KeysToRemoveDict2, BatchData} = lists:foldl(
1186                    fun({K, V}, {KeysToRemoveAcc, BinOpAcc}) ->
1187                        Bin = couch_set_view_updater_helper:encode_op(
1188                            insert, K, V),
1189                        BinOpAcc2 = [Bin | BinOpAcc],
1190                        case dict:find(K, KeysToRemoveAcc) of
1191                        {ok, _} ->
1192                            {dict:erase(K, KeysToRemoveAcc), BinOpAcc2};
1193                        _ ->
1194                            {KeysToRemoveAcc, BinOpAcc2}
1195                        end
1196                    end,
1197                    {KeysToRemoveDict, []}, AddKeyValuesBinaries);
1198            % In r-trees there are multiple possible paths to a key. Hence it's
1199            % not easily possible to replace an existing node with a new one,
1200            % as the insertion could happen in a subtree that is different
1201            % from the subtree of the old value.
1202            spatial_view ->
1203                BatchData = [
1204                    couch_set_view_updater_helper:encode_op(insert, K, V) ||
1205                        {K, V} <- AddKeyValuesBinaries],
1206                KeysToRemoveDict2 = KeysToRemoveDict
1207            end,
1208
1209            BatchData2 = dict:fold(
1210                fun(K, _V, BatchAcc) ->
1211                    Bin = couch_set_view_updater_helper:encode_op(remove, K),
1212                    [Bin | BatchAcc]
1213                end,
1214                BatchData, KeysToRemoveDict2),
1215
1216            ViewTmpFileInfo = dict:fetch(ViewId, TmpFiles),
1217            case ViewTmpFileInfo of
1218            #set_view_tmp_file_info{fd = nil} ->
1219                0 = ViewTmpFileInfo#set_view_tmp_file_info.size,
1220                ViewTmpFilePath = new_sort_file_name(WriterAcc),
1221                {ok, ViewTmpFileFd} = file2:open(
1222                    ViewTmpFilePath, [raw, append, binary]),
1223                ViewTmpFileSize = 0;
1224            #set_view_tmp_file_info{fd = ViewTmpFileFd,
1225                                    size = ViewTmpFileSize,
1226                                    name = ViewTmpFilePath} ->
1227                ok
1228            end,
1229            ok = file:write(ViewTmpFileFd, BatchData2),
1230            ViewTmpFileInfo2 = ViewTmpFileInfo#set_view_tmp_file_info{
1231                fd = ViewTmpFileFd,
1232                name = ViewTmpFilePath,
1233                size = ViewTmpFileSize + iolist_size(BatchData2)
1234            },
1235            dict:store(ViewId, ViewTmpFileInfo2, AccTmpFiles)
1236        end,
1237    TmpFiles, ViewKeyValues),
1238    WriterAcc#writer_acc{
1239        tmp_files = TmpFiles2
1240    }.
1241
1242
1243is_new_partition(PartId, #writer_acc{initial_seqs = InitialSeqs}) ->
1244    couch_util:get_value(PartId, InitialSeqs, 0) == 0.
1245
1246
1247% For incremental index updates.
1248maybe_update_btrees(WriterAcc0) ->
1249    #writer_acc{
1250        view_empty_kvs = ViewEmptyKVs,
1251        tmp_files = TmpFiles,
1252        group = Group0,
1253        final_batch = IsFinalBatch,
1254        owner = Owner,
1255        last_seqs = LastSeqs,
1256        part_versions = PartVersions,
1257        force_flush = ForceFlush
1258    } = WriterAcc0,
1259    IdTmpFileInfo = dict:fetch(ids_index, TmpFiles),
1260    ShouldFlushViews =
1261        lists:any(
1262            fun({#set_view{id_num = Id}, _}) ->
1263                ViewTmpFileInfo = dict:fetch(Id, TmpFiles),
1264                ViewTmpFileInfo#set_view_tmp_file_info.size >= ?INC_MAX_TMP_FILE_SIZE
1265            end, ViewEmptyKVs),
1266    ShouldFlush = IsFinalBatch orelse
1267        ForceFlush orelse
1268        ((IdTmpFileInfo#set_view_tmp_file_info.size >= ?INC_MAX_TMP_FILE_SIZE) andalso
1269        ShouldFlushViews),
1270    case ShouldFlush of
1271    false ->
1272        NewLastSeqs1 = LastSeqs,
1273        case erlang:get(updater_worker) of
1274        undefined ->
1275            WriterAcc = WriterAcc0;
1276        UpdaterWorker when is_reference(UpdaterWorker) ->
1277            receive
1278            {UpdaterWorker, UpGroup, UpStats, CompactFiles} ->
1279                send_log_compact_files(Owner, CompactFiles, ?set_seqs(UpGroup),
1280                    ?set_partition_versions(UpGroup)),
1281                erlang:erase(updater_worker),
1282                WriterAcc = check_if_compactor_started(
1283                    WriterAcc0#writer_acc{group = UpGroup, stats = UpStats})
1284            after 0 ->
1285                WriterAcc = WriterAcc0
1286            end
1287        end;
1288    true ->
1289        ok = close_tmp_fd(IdTmpFileInfo),
1290        ok = lists:foreach(
1291            fun(#set_view{id_num = Id}) ->
1292                ViewTmpFileInfo = dict:fetch(Id, TmpFiles),
1293                ok = close_tmp_fd(ViewTmpFileInfo)
1294            end,
1295            Group0#set_view_group.views),
1296        case erlang:erase(updater_worker) of
1297        undefined ->
1298            WriterAcc1 = WriterAcc0;
1299        UpdaterWorker when is_reference(UpdaterWorker) ->
1300            receive
1301            {UpdaterWorker, UpGroup2, UpStats2, CompactFiles2} ->
1302                send_log_compact_files(Owner, CompactFiles2, ?set_seqs(UpGroup2),
1303                    ?set_partition_versions(UpGroup2)),
1304                WriterAcc1 = check_if_compactor_started(
1305                    WriterAcc0#writer_acc{
1306                        group = UpGroup2,
1307                        stats = UpStats2
1308                    })
1309            end
1310        end,
1311
1312
1313        % MB-11472: There is no id sortfile present and hence this is the final batch
1314        % and nothing left to be updated to the btree
1315        case IdTmpFileInfo#set_view_tmp_file_info.name of
1316        nil ->
1317            WriterAcc = WriterAcc1;
1318        _ ->
1319            WriterAcc2 = check_if_compactor_started(WriterAcc1),
1320            NewUpdaterWorker = spawn_updater_worker(WriterAcc2, LastSeqs, PartVersions),
1321            erlang:put(updater_worker, NewUpdaterWorker),
1322
1323            TmpFiles2 = dict:map(
1324                fun(_, _) -> #set_view_tmp_file_info{} end, TmpFiles),
1325            WriterAcc = WriterAcc2#writer_acc{tmp_files = TmpFiles2}
1326        end,
1327        NewLastSeqs1 = orddict:new()
1328    end,
1329    #writer_acc{
1330        stats = NewStats0,
1331        group = NewGroup0
1332    } = WriterAcc,
1333    case IsFinalBatch of
1334    true ->
1335        case erlang:erase(updater_worker) of
1336        undefined ->
1337            NewGroup = NewGroup0,
1338            NewStats = NewStats0;
1339        UpdaterWorker2 when is_reference(UpdaterWorker2) ->
1340            receive
1341            {UpdaterWorker2, NewGroup, NewStats, CompactFiles3} ->
1342                send_log_compact_files(Owner, CompactFiles3, ?set_seqs(NewGroup),
1343                    ?set_partition_versions(NewGroup))
1344            end
1345        end,
1346        NewLastSeqs = orddict:new();
1347    false ->
1348        NewGroup = NewGroup0,
1349        NewStats = NewStats0,
1350        NewLastSeqs = NewLastSeqs1
1351    end,
1352    NewWriterAcc = WriterAcc#writer_acc{
1353        stats = NewStats,
1354        group = NewGroup,
1355        last_seqs = NewLastSeqs
1356    },
1357    NewWriterAcc.
1358
1359
1360send_log_compact_files(_Owner, [], _Seqs, _PartVersions) ->
1361    ok;
1362send_log_compact_files(Owner, Files, Seqs, PartVersions) ->
1363    Init = case erlang:erase(new_compactor) of
1364    true ->
1365        true;
1366    undefined ->
1367        false
1368    end,
1369    ok = gen_server:cast(Owner, {compact_log_files, Files, Seqs, PartVersions, Init}).
1370
1371
1372-spec spawn_updater_worker(#writer_acc{}, partition_seqs(),
1373                           partition_versions()) -> reference().
1374spawn_updater_worker(WriterAcc, PartIdSeqs, PartVersions) ->
1375    Parent = self(),
1376    Ref = make_ref(),
1377    #writer_acc{
1378        group = Group,
1379        parent = UpdaterPid,
1380        max_seqs = MaxSeqs
1381    } = WriterAcc,
1382    % Wait for main updater process to ack
1383    UpdaterPid ! {native_updater_start, self()},
1384    receive
1385    {ok, native_updater_start} ->
1386        ok
1387    end,
1388    Pid = spawn_link(fun() ->
1389        case ?set_cbitmask(Group) of
1390        0 ->
1391            CleanupStart = 0;
1392        _ ->
1393            CleanupStart = os:timestamp()
1394        end,
1395        {ok, NewGroup0, CleanupCount, NewStats, NewCompactFiles} = update_btrees(WriterAcc),
1396        case ?set_cbitmask(Group) of
1397        0 ->
1398            CleanupTime = 0.0;
1399        _ ->
1400            CleanupTime = timer:now_diff(os:timestamp(), CleanupStart) / 1000000,
1401            #set_view_group{
1402                set_name = SetName,
1403                name = DDocId,
1404                type = GroupType
1405            } = Group,
1406            ?LOG_INFO("Updater for set view `~s`, ~s group `~s`, performed cleanup "
1407                      "of ~p key/value pairs in ~.3f seconds",
1408                      [SetName, GroupType, DDocId, CleanupCount, CleanupTime])
1409        end,
1410        NewSeqs = update_seqs(PartIdSeqs, ?set_seqs(Group)),
1411        NewPartVersions = update_versions(PartVersions, ?set_partition_versions(Group)),
1412        Header = NewGroup0#set_view_group.index_header,
1413        NewHeader = Header#set_view_index_header{
1414            seqs = NewSeqs,
1415            partition_versions = NewPartVersions
1416        },
1417        NewGroup = NewGroup0#set_view_group{
1418            index_header = NewHeader
1419        },
1420        NewGroup2 = update_transferred_replicas(NewGroup, MaxSeqs, PartIdSeqs),
1421        NumChanges = count_seqs_done(Group, NewSeqs),
1422        NewStats2 = NewStats#set_view_updater_stats{
1423           seqs = NewStats#set_view_updater_stats.seqs + NumChanges,
1424           cleanup_time = NewStats#set_view_updater_stats.seqs + CleanupTime,
1425           cleanup_kv_count = NewStats#set_view_updater_stats.cleanup_kv_count + CleanupCount
1426        },
1427        Parent ! {Ref, NewGroup2, NewStats2, NewCompactFiles}
1428    end),
1429    UpdaterPid ! {native_updater_pid, Pid},
1430    Ref.
1431
1432% Update id btree and view btrees with current batch of changes
1433update_btrees(WriterAcc) ->
1434    #writer_acc{
1435        stats = Stats,
1436        group = Group0,
1437        tmp_dir = TmpDir,
1438        tmp_files = TmpFiles,
1439        compactor_running = CompactorRunning,
1440        max_insert_batch_size = MaxBatchSize
1441    } = WriterAcc,
1442
1443    % Prepare list of operation logs for each btree
1444    #set_view_tmp_file_info{name = IdFile} = dict:fetch(ids_index, TmpFiles),
1445    ViewFiles = lists:map(
1446        fun(#set_view{id_num = Id}) ->
1447            #set_view_tmp_file_info{
1448                name = ViewFile
1449            } = dict:fetch(Id, TmpFiles),
1450            ViewFile
1451        end, Group0#set_view_group.views),
1452    % `LogFiles` is supplied to the native updater. For spatial views only the
1453    % ID b-tree is updated.
1454    LogFiles = case Group0#set_view_group.mod of
1455    mapreduce_view ->
1456        [IdFile | ViewFiles];
1457    spatial_view ->
1458        [IdFile]
1459    end,
1460
1461    % Remove spatial views from group
1462    % The native updater can currently handle mapreduce views only, but it
1463    % handles the ID b-tree of the spatial view
1464    Group = couch_set_view_util:remove_group_views(Group0, spatial_view),
1465
1466    {ok, NewGroup0, Stats2} = couch_set_view_updater_helper:update_btrees(
1467        Group, TmpDir, LogFiles, MaxBatchSize, false),
1468    {IdsInserted, IdsDeleted, KVsInserted, KVsDeleted, CleanupCount} = Stats2,
1469
1470    % Add back spatial views
1471    NewGroup = couch_set_view_util:update_group_views(
1472        NewGroup0, Group0, spatial_view),
1473
1474    % The native update for the Id b-tree was run, now it's time to run the
1475    % Erlang updater for the spatial views
1476    NewGroup2 = case NewGroup#set_view_group.mod of
1477    mapreduce_view ->
1478        NewGroup;
1479    spatial_view = Mod ->
1480        process_flag(trap_exit, true),
1481        ok = couch_file:refresh_eof(NewGroup#set_view_group.fd),
1482        Pid = spawn_link(fun() ->
1483            Views = Mod:update_spatial(NewGroup#set_view_group.views, ViewFiles,
1484                MaxBatchSize),
1485            exit({spatial_views_updater_result, Views})
1486            end),
1487        receive
1488        {'EXIT', Pid, Result} ->
1489            case Result of
1490            {spatial_views_updater_result, Views} ->
1491                NewGroup#set_view_group{
1492                    views = Views,
1493                    index_header = (NewGroup#set_view_group.index_header)#set_view_index_header{
1494                        view_states = [Mod:get_state(V#set_view.indexer) || V <- Views]
1495                    }
1496                };
1497            _ ->
1498                exit(Result)
1499            end;
1500        stop ->
1501            #set_view_group{
1502                set_name = SetName,
1503                name = DDocId,
1504                type = Type
1505            } = NewGroup,
1506            ?LOG_INFO("Set view `~s`, ~s group `~s`, index updater (spatial"
1507                      "update) stopped successfully.", [SetName, Type, DDocId]),
1508            couch_util:shutdown_sync(Pid),
1509            exit(shutdown)
1510        end
1511    end,
1512
1513    NewStats = Stats#set_view_updater_stats{
1514     inserted_ids = Stats#set_view_updater_stats.inserted_ids + IdsInserted,
1515     deleted_ids = Stats#set_view_updater_stats.deleted_ids + IdsDeleted,
1516     inserted_kvs = Stats#set_view_updater_stats.inserted_kvs + KVsInserted,
1517     deleted_kvs = Stats#set_view_updater_stats.deleted_kvs + KVsDeleted
1518    },
1519
1520    % Remove files if compactor is not running
1521    % Otherwise send them to compactor to apply deltas
1522    CompactFiles = lists:foldr(
1523        fun(SortedFile, AccCompactFiles) ->
1524            case CompactorRunning of
1525            true ->
1526                case filename:extension(SortedFile) of
1527                ".compact" ->
1528                     [SortedFile | AccCompactFiles];
1529                _ ->
1530                    SortedFile2 = new_sort_file_name(TmpDir, true),
1531                    ok = file2:rename(SortedFile, SortedFile2),
1532                    [SortedFile2 | AccCompactFiles]
1533                end;
1534            false ->
1535                ok = file2:delete(SortedFile),
1536                AccCompactFiles
1537            end
1538        end, [], [IdFile | ViewFiles]),
1539    {ok, NewGroup2, CleanupCount, NewStats, CompactFiles}.
1540
1541
1542update_seqs(PartIdSeqs, Seqs) ->
1543    orddict:fold(
1544        fun(PartId, NewSeq, Acc) ->
1545            OldSeq = couch_util:get_value(PartId, Acc, 0),
1546            case NewSeq > OldSeq of
1547            true ->
1548                ok;
1549            false ->
1550                exit({error, <<"New seq smaller or equal than old seq.">>, PartId, OldSeq, NewSeq})
1551            end,
1552            orddict:store(PartId, NewSeq, Acc)
1553        end,
1554        Seqs, PartIdSeqs).
1555
1556update_versions(PartVersions, AllPartVersions) ->
1557    lists:ukeymerge(1, PartVersions, AllPartVersions).
1558
1559
1560update_task(NumChanges) ->
1561    [Changes, Total] = couch_task_status:get([changes_done, total_changes]),
1562    Changes2 = Changes + NumChanges,
1563    Total2 = erlang:max(Total, Changes2),
1564    Progress = (Changes2 * 100) div Total2,
1565    couch_task_status:update([
1566        {progress, Progress},
1567        {changes_done, Changes2},
1568        {total_changes, Total2}
1569    ]).
1570
1571
1572checkpoint(#writer_acc{owner = Owner, parent = Parent, group = Group} = Acc) ->
1573    #set_view_group{
1574        set_name = SetName,
1575        name = DDocId,
1576        type = Type
1577    } = Group,
1578    ?LOG_INFO("Updater checkpointing set view `~s` update for ~s group `~s`",
1579              [SetName, Type, DDocId]),
1580    NewGroup = maybe_fix_group(Group),
1581    ok = couch_file:refresh_eof(NewGroup#set_view_group.fd),
1582    Owner ! {partial_update, Parent, self(), NewGroup},
1583    receive
1584    update_processed ->
1585        ok;
1586    stop ->
1587        exit(shutdown)
1588    end,
1589    Acc#writer_acc{group = NewGroup}.
1590
1591
1592maybe_fix_group(#set_view_group{index_header = Header} = Group) ->
1593    receive
1594    {new_passive_partitions, Parts} ->
1595        Bitmask = couch_set_view_util:build_bitmask(Parts),
1596        {Seqs, PartVersions} = couch_set_view_util:fix_partitions(Group, Parts),
1597        Group#set_view_group{
1598            index_header = Header#set_view_index_header{
1599                seqs = Seqs,
1600                pbitmask = ?set_pbitmask(Group) bor Bitmask,
1601                partition_versions = PartVersions
1602            }
1603        }
1604    after 0 ->
1605        Group
1606    end.
1607
1608
1609check_if_compactor_started(#writer_acc{group = Group0} = Acc) ->
1610    receive
1611    {compactor_started, Pid} ->
1612        erlang:put(new_compactor, true),
1613        Group = maybe_fix_group(Group0),
1614        Pid ! {compactor_started_ack, self(), Group},
1615        Acc#writer_acc{compactor_running = true, group = Group}
1616    after 0 ->
1617        Acc
1618    end.
1619
1620
1621init_tmp_files(WriterAcc) ->
1622    #writer_acc{
1623        group = Group, initial_build = Init, tmp_dir = TmpDir
1624    } = WriterAcc,
1625    case WriterAcc#writer_acc.compactor_running of
1626    true ->
1627        ok = couch_set_view_util:delete_sort_files(TmpDir, updater);
1628    false ->
1629        ok = couch_set_view_util:delete_sort_files(TmpDir, all)
1630    end,
1631    Ids = [ids_index | [V#set_view.id_num || V <- Group#set_view_group.views]],
1632    Files = case Init of
1633    true ->
1634        [begin
1635             FileName = new_sort_file_name(WriterAcc),
1636             {ok, Fd} = file2:open(FileName, [raw, append, binary]),
1637             {Id, #set_view_tmp_file_info{fd = Fd, name = FileName}}
1638         end || Id <- Ids];
1639    false ->
1640         [{Id, #set_view_tmp_file_info{}} || Id <- Ids]
1641    end,
1642    WriterAcc#writer_acc{tmp_files = dict:from_list(Files)}.
1643
1644
1645new_sort_file_name(#writer_acc{tmp_dir = TmpDir, compactor_running = Cr}) ->
1646    new_sort_file_name(TmpDir, Cr).
1647
1648new_sort_file_name(TmpDir, true) ->
1649    couch_set_view_util:new_sort_file_path(TmpDir, compactor);
1650new_sort_file_name(TmpDir, false) ->
1651    couch_set_view_util:new_sort_file_path(TmpDir, updater).
1652
1653
1654make_back_index_key(DocId, PartId) ->
1655    <<PartId:16, DocId/binary>>.
1656
1657
1658count_seqs_done(Group, NewSeqs) ->
1659    % NewSeqs might have new passive partitions that Group's seqs doesn't
1660    % have yet (will get them after a checkpoint period).
1661    lists:foldl(
1662        fun({PartId, SeqDone}, Acc) ->
1663            SeqBefore = couch_util:get_value(PartId, ?set_seqs(Group), 0),
1664            Acc + (SeqDone - SeqBefore)
1665        end,
1666        0, NewSeqs).
1667
1668
1669close_tmp_fd(#set_view_tmp_file_info{fd = nil}) ->
1670    ok;
1671close_tmp_fd(#set_view_tmp_file_info{fd = Fd}) ->
1672    ok = file:close(Fd).
1673
1674
1675% DCP introduces the concept of snapshots, where a document mutation is only
1676% guaranteed to be unique within a single snapshot. But the flusher expects
1677% unique mutations within the full batch. Merge multiple snapshots (if there
1678% are any) into a single one. The latest mutation wins.
1679merge_snapshots(KVs) ->
1680    merge_snapshots(KVs, false, []).
1681
1682merge_snapshots([], true, Acc) ->
1683    {true, Acc};
1684merge_snapshots([], false, Acc) ->
1685    % The order of the KVs doesn't really matter, but having them sorted the
1686    % same way will make life easier when debugging
1687    {false, lists:reverse(Acc)};
1688merge_snapshots([snapshot_marker | KVs], _MultipleSnapshots, Acc) ->
1689    merge_snapshots(KVs, true, Acc);
1690merge_snapshots([{part_versions, _} = PartVersions | KVs], MultipleSnapshots, Acc) ->
1691    merge_snapshots(KVs, MultipleSnapshots, [PartVersions | Acc]);
1692merge_snapshots([KV | KVs], true, Acc0) ->
1693    {_Seq, DocId, _PartId, _QueryResults} = KV,
1694    Acc = lists:keystore(DocId, 2, Acc0, KV),
1695    merge_snapshots(KVs, true, Acc);
1696merge_snapshots([KV | KVs], false, Acc) ->
1697    merge_snapshots(KVs, false, [KV | Acc]).
1698