anchor.diff:  -module(stats_archiver).
   
   -include_lib("eunit/include/eunit.hrl").
  +-include_lib("stdlib/include/qlc.hrl").
   
   -include("ns_common.hrl").
   -include("ns_stats.hrl").
  
positive.code: 
  
  handle_call({latest, Period, Bucket}, _From, State) ->
      Reply = try mnesia:transaction(
                    fun () ->
                            Tab = table(Bucket, Period),
                            Key = mnesia:last(Tab),
                            hd(mnesia:read(Tab, Key))
                    end, ?RETRIES) of
                  {atomic, Result} ->
                      {ok, Result};
                  Err ->
                      {error, Err}
              catch
                  Type:Err -> {error, {Type, Err}}
              end,
      {reply, Reply, State};
  handle_call({latest, Period, Bucket, N}, _From, State) ->
      Reply = try walk(table(Bucket, Period), N) of
                  Result -> {ok, Result}
              catch
                  Type:Err -> {error, {Type, Err}}
              end,
      {reply, Reply, State};
  handle_call({latest, Period, Bucket, Step, N}, _From, State) ->
      Reply = try resample(table(Bucket, Period), Step, N) of
                  Result -> {ok, Result}
              catch
                  Type:Err -> {error, {Type, Err}}
              end,
      {reply, Reply, State}.
  
  
  
negative.code:       end, archives()).
  
  
  %% @doc Return the last N records starting with the given key from Tab.
  fetch_latest(Bucket, Period, N) ->
      case lists:keyfind(Period, 1, archives()) of
          false ->
              {error, bad_period, Period};
          {_, Interval, _} ->
              Seconds = N * Interval,
              Tab = table(Bucket, Period),
              case mnesia:dirty_last(Tab) of
                  '$end_of_table' ->
                      {ok, []};
                  Key ->
                      Oldest = Key - Seconds * 1000 + 500,
                      Handle = qlc:q([Sample || #stat_entry{timestamp=TS} = Sample
                                                    <- mnesia:table(Tab), TS > Oldest]),
                      case mnesia:activity(async_dirty, fun qlc:eval/1, [Handle]) of
                          {error, _, _} = Error ->
                              Error;
                          Results ->
                              {ok, Results}
                      end
              end
      end.
  
  
  last_chunk(Tab, Step) ->
      case mnesia:last(Tab) of
          '$end_of_table' ->
  