anchor.diff:              maybe_start_replication(State, DocId, JsonRepDoc);
           <<"triggered">> ->
               maybe_start_replication(State, DocId, JsonRepDoc);
  -        _ ->
  -           State
  +        <<"completed">> ->
  +            replication_complete(DocId),
  +            State;
  +        <<"error">> ->
  +            replication_error(State, DocId)
           end
       end.
   
  
positive.code: update_rep_doc(RepDocId, KVs) ->
      {ok, RepDb} = ensure_rep_db_exists(),
      try
          {ok, LatestRepDoc} = couch_db:open_doc(RepDb, RepDocId, []),
          update_rep_doc(RepDb, LatestRepDoc, KVs)
      catch throw:conflict ->
          % Shouldn't happen, as by default only the role _replicator can
          % update replication documents.
  
negative.code:     end.
  
  
  replication_error(State, DocId) ->
      case ets:lookup(?DOC_TO_REP, DocId) of
      [{DocId, RepId}] ->
          maybe_retry_replication(rep_state(RepId), State);
      _ ->
          State
      end.
  
  maybe_retry_replication(#rep_state{retries_left = 0} = RepState, State) ->
      #rep_state{
          rep = #rep{id = RepId, doc_id = DocId},
          max_retries = MaxRetries,
          last_error = Error
      } = RepState,
      couch_replicator:cancel_replication(RepId),
      true = ets:delete(?REP_TO_STATE, RepId),
      true = ets:delete(?DOC_TO_REP, DocId),
      ?LOG_ERROR("Error in replication `~s` (triggered by document `~s`): ~s"
          "~nReached maximum retry attempts (~p).",
          [pp_rep_id(RepId), DocId, to_binary(error_reason(Error)), MaxRetries]),
      State;
  
  maybe_retry_replication(RepState, State) ->
      #rep_state{
          rep = #rep{id = RepId, doc_id = DocId} = Rep,
          retries_left = RetriesLeft,
          last_error = Error
      } = RepState,
      NewRepState = RepState#rep_state{retries_left = RetriesLeft - 1},
      true = ets:insert(?REP_TO_STATE, {RepId, NewRepState}),
      Wait = wait_period(NewRepState),
      ?LOG_ERROR("Error in replication `~s` (triggered by document `~s`): ~s"
          "~nRestarting replication in ~p seconds.",
          [pp_rep_id(RepId), DocId, to_binary(error_reason(Error)), Wait]),
      Server = self(),
      Pid = spawn_link(fun() -> start_replication(Server, Rep, Wait) end),
      State#state{rep_start_pids = [Pid | State#state.rep_start_pids]}.
  
  
  stop_all_replications() ->
      ?LOG_INFO("Stopping all ongoing replications because the replicator"
          " database was deleted or changed", []),
  