aboutsummaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/attribute/reference_attribute.cpp
blob: 5b957af74fd4fec2b8fc7bc1d3eca7946900226c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "attributesaver.h"
#include "load_utils.h"
#include "readerbase.h"
#include "reference_attribute.h"
#include "reference_attribute_saver.h"
#include <vespa/document/base/documentid.h>
#include <vespa/document/base/idstringexception.h>
#include <vespa/searchlib/common/i_gid_to_lid_mapper.h>
#include <vespa/searchlib/common/i_gid_to_lid_mapper_factory.h>
#include <vespa/searchlib/query/query_term_simple.h>
#include <vespa/vespalib/data/fileheader.h>
#include <vespa/vespalib/datastore/unique_store_builder.h>
#include <vespa/vespalib/datastore/datastore.hpp>
#include <vespa/vespalib/datastore/unique_store.hpp>
#include <vespa/vespalib/datastore/buffer_type.hpp>

#include <vespa/log/log.h>
LOG_SETUP(".searchlib.attribute.reference_attribute");

namespace search::attribute {

using document::DocumentId;
using document::GlobalId;
using document::IdParseException;
using vespalib::datastore::CompactionSpec;

namespace {

const vespalib::string uniqueValueCountTag = "uniqueValueCount";

uint64_t
extractUniqueValueCount(const vespalib::GenericHeader &header)
{
    return (header.hasTag(uniqueValueCountTag)) ? header.getTag(uniqueValueCountTag).asInteger() : 0u;
}

}

ReferenceAttribute::ReferenceAttribute(const vespalib::stringref baseFileName,
                                       const Config & cfg)
    : NotImplementedAttribute(baseFileName, cfg),
      _store({}),
      _indices(getGenerationHolder()),
      _compaction_spec(),
      _gidToLidMapperFactory(),
      _referenceMappings(getGenerationHolder(), getCommittedDocIdLimitRef())
{
    setEnum(true);
}

ReferenceAttribute::~ReferenceAttribute()
{
    _referenceMappings.clearBuilder();
    incGeneration(); // Force freeze
    const auto &store = _store;
    const auto enumerator = _store.getEnumerator(true);
    enumerator.foreach_key([&store,this](const AtomicEntryRef& ref)
                      {   const Reference &entry = store.get(ref.load_relaxed());
                          _referenceMappings.clearMapping(entry);
                      });
    incGeneration(); // Force freeze
}

void
ReferenceAttribute::onAddDocs(DocId limit)
{
    _indices.reserve(limit);
    _referenceMappings.onAddDocs(limit);
}

bool
ReferenceAttribute::addDoc(DocId &doc)
{
    bool incGen = _indices.isFull();
    doc = _indices.size();
    _indices.push_back(AtomicEntryRef());
    _referenceMappings.addDoc();
    incNumDocs();
    updateUncommittedDocIdLimit(doc);
    if (incGen) {
        incGeneration();
    } else {
        removeAllOldGenerations();
    }
    return true;
}

void
ReferenceAttribute::removeReverseMapping(EntryRef oldRef, uint32_t lid)
{
    const auto &entry = _store.get(oldRef);
    _referenceMappings.removeReverseMapping(entry, lid);
}

void
ReferenceAttribute::addReverseMapping(EntryRef newRef, uint32_t lid)
{
    const auto &entry = _store.get(newRef);
    _referenceMappings.addReverseMapping(entry, lid);
}

void
ReferenceAttribute::buildReverseMapping(EntryRef newRef, const std::vector<ReverseMapping::KeyDataType> &adds)
{
    const auto &entry = _store.get(newRef);
    _referenceMappings.buildReverseMapping(entry, adds);
}

void
ReferenceAttribute::buildReverseMapping()
{
    using EntryPair = std::pair<EntryRef, uint32_t>;
    std::vector<EntryPair, vespalib::allocator_large<EntryPair>> indices;
    uint32_t numDocs = _indices.size();
    indices.reserve(numDocs);
    for (uint32_t lid = 0; lid < numDocs; ++lid) {
        EntryRef ref = _indices[lid].load_relaxed();
        if (ref.valid()) {
            indices.emplace_back(ref, lid);
        }
    }
    std::sort(indices.begin(), indices.end());
    EntryRef prevRef;
    std::vector<ReverseMapping::KeyDataType> adds;
    for (const auto & elem : indices) {
        if (elem.first != prevRef) {
            if (prevRef.valid()) {
                buildReverseMapping(prevRef, adds);
                adds.clear();
            }
            prevRef = elem.first;
        }
        adds.emplace_back(elem.second, vespalib::btree::BTreeNoLeafData());
    }
    if (prevRef.valid()) {
        buildReverseMapping(prevRef, adds);
    }
}

uint32_t
ReferenceAttribute::clearDoc(DocId doc)
{
    updateUncommittedDocIdLimit(doc);
    assert(doc < _indices.size());
    EntryRef oldRef = _indices[doc].load_relaxed();
    if (oldRef.valid()) {
        removeReverseMapping(oldRef, doc);
        _indices[doc].store_release(EntryRef());
        _store.remove(oldRef);
        return 1u;
    } else {
        return 0u;
    }
}

void
ReferenceAttribute::removeOldGenerations(generation_t firstUsed)
{
    _referenceMappings.trimHoldLists(firstUsed);
    _store.trimHoldLists(firstUsed);
    getGenerationHolder().trimHoldLists(firstUsed);
}

void
ReferenceAttribute::onGenerationChange(generation_t generation)
{
    _referenceMappings.freeze();
    _store.freeze();
    _referenceMappings.transferHoldLists(generation - 1);
    _store.transferHoldLists(generation - 1);
    getGenerationHolder().transferHoldLists(generation - 1);
}

void
ReferenceAttribute::onCommit()
{
    // Note: Cost can be reduced if unneeded generation increments are dropped
    incGeneration();
    if (consider_compact_values(getConfig().getCompactionStrategy())) {
        incGeneration();
        updateStat(true);
    }
    if (consider_compact_dictionary(getConfig().getCompactionStrategy())) {
        incGeneration();
        updateStat(true);
    }
}

void
ReferenceAttribute::onUpdateStat()
{
    auto& compaction_strategy = getConfig().getCompactionStrategy();
    vespalib::MemoryUsage total = _store.get_values_memory_usage();
    auto& dictionary = _store.get_dictionary();
    auto dictionary_memory_usage = dictionary.get_memory_usage();
    _compaction_spec = ReferenceAttributeCompactionSpec(compaction_strategy.should_compact_memory(total),
                                                        compaction_strategy.should_compact_memory(dictionary_memory_usage));
    total.merge(dictionary_memory_usage);
    total.mergeGenerationHeldBytes(getGenerationHolder().getHeldBytes());
    total.merge(_indices.getMemoryUsage());
    total.merge(_referenceMappings.getMemoryUsage());
    updateStatistics(getTotalValueCount(), getUniqueValueCount(),
                     total.allocatedBytes(),
                     total.usedBytes(), total.deadBytes(), total.allocatedBytesOnHold());
}

std::unique_ptr<AttributeSaver>
ReferenceAttribute::onInitSave(vespalib::stringref fileName)
{
    vespalib::GenerationHandler::Guard guard(this->getGenerationHandler().takeGuard());
    return std::make_unique<ReferenceAttributeSaver>
        (std::move(guard),
         createAttributeHeader(fileName),
         getIndicesCopy(getCommittedDocIdLimit()),
         _store);
}

bool
ReferenceAttribute::onLoad(vespalib::Executor *)
{
    ReaderBase attrReader(*this);
    bool ok(attrReader.getHasLoadData());
    if (!ok) {
        return false;
    }
    setCreateSerialNum(attrReader.getCreateSerialNum());
    assert(attrReader.getEnumerated());
    assert(!attrReader.hasIdx());
    size_t numDocs(0);
    uint64_t numValues = attrReader.getEnumCount();
    numDocs = numValues;
    auto udatBuffer = attribute::LoadUtils::loadUDAT(*this);
    const GenericHeader &header = udatBuffer->getHeader();
    uint32_t uniqueValueCount = extractUniqueValueCount(header);
    assert(uniqueValueCount * sizeof(GlobalId) == udatBuffer->size());
    vespalib::ConstArrayRef<GlobalId> uniques(static_cast<const GlobalId *>(udatBuffer->buffer()), uniqueValueCount);

    auto builder = _store.getBuilder(uniqueValueCount);
    for (const auto &value : uniques) {
        builder.add(value);
    }
    builder.setupRefCounts();
    _referenceMappings.onLoad(numDocs);
    _indices.clear();
    _indices.unsafe_reserve(numDocs);
    for (uint32_t doc = 0; doc < numDocs; ++doc) {
        uint32_t enumValue = attrReader.getNextEnum();
        _indices.push_back(AtomicEntryRef(builder.mapEnumValueToEntryRef(enumValue)));
    }
    builder.makeDictionary();
    setNumDocs(numDocs);
    setCommittedDocIdLimit(numDocs);
    buildReverseMapping();
    incGeneration();
    return true;
}

void
ReferenceAttribute::update(DocId doc, const GlobalId &gid)
{
    updateUncommittedDocIdLimit(doc);
    assert(doc < _indices.size());
    EntryRef oldRef = _indices[doc].load_relaxed();
    Reference refToAdd(gid);
    EntryRef newRef = _store.add(refToAdd).ref();
    std::atomic_thread_fence(std::memory_order_release);
    _indices[doc].store_release(newRef);
    if (oldRef.valid()) {
        if (oldRef != newRef) {
            removeReverseMapping(oldRef, doc);
        }
        _store.remove(oldRef);
    }
    if (oldRef != newRef) {
        addReverseMapping(newRef, doc);
    }
}

const Reference *
ReferenceAttribute::getReference(DocId doc) const
{
    if (doc >= getCommittedDocIdLimit()) {
        return nullptr;
    }
    EntryRef ref = _indices.acquire_elem_ref(doc).load_acquire();
    if (!ref.valid()) {
        return nullptr;
    } else {
        return &_store.get(ref);
    }
}

bool
ReferenceAttribute::consider_compact_values(const CompactionStrategy &compactionStrategy)
{
    if (_compaction_spec.values()) {
        compact_worst_values(compactionStrategy);
        return true;
    }
    return false;
}

void
ReferenceAttribute::compact_worst_values(const CompactionStrategy& compaction_strategy)
{
    CompactionSpec compaction_spec(true, true);
    auto remapper(_store.compact_worst(compaction_spec, compaction_strategy));
    if (remapper) {
        remapper->remap(vespalib::ArrayRef<AtomicEntryRef>(&_indices[0], _indices.size()));
        remapper->done();
    }
}

bool
ReferenceAttribute::consider_compact_dictionary(const CompactionStrategy &compaction_strategy)
{
    auto& dictionary = _store.get_dictionary();
    if (dictionary.has_held_buffers()) {
        return false;
    }
    if (_compaction_spec.dictionary()) {
        dictionary.compact_worst(true, true, compaction_strategy);
        return true;
    }
    return false;
}

uint64_t
ReferenceAttribute::getUniqueValueCount() const
{
    return _store.getNumUniques();
}

ReferenceAttribute::IndicesCopyVector
ReferenceAttribute::getIndicesCopy(uint32_t size) const
{
    assert(size <= _indices.size());
    IndicesCopyVector result;
    result.reserve(size);
    for (uint32_t i = 0; i < size; ++i) {
        result.push_back(_indices[i].load_relaxed());
    }
    return result;
}

void
ReferenceAttribute::setGidToLidMapperFactory(std::shared_ptr<IGidToLidMapperFactory> gidToLidMapperFactory)
{
    _gidToLidMapperFactory = std::move(gidToLidMapperFactory);
}

void
ReferenceAttribute::notifyReferencedPutNoCommit(const GlobalId &gid, DocId targetLid)
{
    assert(targetLid != 0);
    EntryRef ref = _store.find(gid);
    if (!ref.valid() || _store.get(ref).lid() == 0) {
        Reference refToAdd(gid);
        ref = _store.add(refToAdd).ref();
    }
    const auto &entry = _store.get(ref);
    _referenceMappings.notifyReferencedPut(entry, targetLid);
}

void
ReferenceAttribute::notifyReferencedPut(const GlobalId &gid, DocId targetLid)
{
    notifyReferencedPutNoCommit(gid, targetLid);
    commit();
}

bool
ReferenceAttribute::notifyReferencedRemoveNoCommit(const GlobalId &gid)
{
    EntryRef ref = _store.find(gid);
    if (ref.valid()) {
        const auto &entry = _store.get(ref);
        uint32_t oldTargetLid = entry.lid();
        _referenceMappings.notifyReferencedRemove(entry);
        if (oldTargetLid != 0) {
            _store.remove(ref);
        }
        return true;
    }
    return false;
}

void
ReferenceAttribute::notifyReferencedRemove(const GlobalId &gid)
{
    if (notifyReferencedRemoveNoCommit(gid)) {
        commit();
    }
}

namespace {

class TargetLidPopulator : public IGidToLidMapperVisitor
{
    ReferenceAttribute &_attr;
public:
    explicit TargetLidPopulator(ReferenceAttribute &attr)
        : IGidToLidMapperVisitor(),
          _attr(attr)
    {
    }
    ~TargetLidPopulator() override = default;
    void visit(const document::GlobalId &gid, uint32_t lid) const override {
        _attr.notifyReferencedPutNoCommit(gid, lid);
    }
};

}

void
ReferenceAttribute::populateTargetLids(const std::vector<GlobalId>& removes)
{
    if (_gidToLidMapperFactory) {
        std::unique_ptr<IGidToLidMapper> mapperUP = _gidToLidMapperFactory->getMapper();
        const IGidToLidMapper &mapper = *mapperUP;
        TargetLidPopulator populator(*this);
        mapper.foreach(populator);
    }
    for (auto& remove : removes) {
        notifyReferencedRemoveNoCommit(remove);
    }
    commit();
}

void
ReferenceAttribute::clearDocs(DocId lidLow, DocId lidLimit)
{
    assert(lidLow <= lidLimit);
    assert(lidLimit <= getNumDocs());
    for (DocId lid = lidLow; lid < lidLimit; ++lid) {
        EntryRef oldRef = _indices[lid].load_relaxed();
        if (oldRef.valid()) {
            removeReverseMapping(oldRef, lid);
            _indices[lid].store_release(EntryRef());
            _store.remove(oldRef);
        }
    }
}

void
ReferenceAttribute::onShrinkLidSpace()
{
    // References for lids > committedDocIdLimit have been cleared.
    uint32_t committedDocIdLimit = getCommittedDocIdLimit();
    assert(_indices.size() >= committedDocIdLimit);
    _indices.shrink(committedDocIdLimit);
    _referenceMappings.shrink(committedDocIdLimit);
    setNumDocs(committedDocIdLimit);
}

namespace {

class ReferenceSearchContext : public AttributeVector::SearchContext {
private:
    const ReferenceAttribute& _ref_attr;
    GlobalId _term;

public:
    ReferenceSearchContext(const ReferenceAttribute& ref_attr, const GlobalId& term)
        : AttributeVector::SearchContext(ref_attr),
          _ref_attr(ref_attr),
          _term(term)
    {
    }
    bool valid() const override {
        return _term != GlobalId();
    }
    int32_t onFind(DocId docId, int32_t elementId, int32_t& weight) const override {
        if (elementId != 0) {
            return -1;
        }
        auto* ref = _ref_attr.getReference(docId);
        if (ref == nullptr) {
            return -1;
        }
        weight = 1;
        return (_term == ref->gid()) ? 0 : -1;
    }
    int32_t onFind(DocId docId, int32_t elementId) const override {
        int32_t weight;
        return onFind(docId, elementId, weight);
    }
};

}

AttributeVector::SearchContext::UP
ReferenceAttribute::getSearch(QueryTermSimpleUP term, const attribute::SearchContextParams& params) const
{
    (void) params;
    GlobalId gid;
    try {
        DocumentId docId(term->getTerm());
        gid = docId.getGlobalId();
    } catch (const IdParseException&) {
        // The query term is not valid, which will result in an empty search iterator.
    }
    return std::make_unique<ReferenceSearchContext>(*this, gid);
}

IMPLEMENT_IDENTIFIABLE_ABSTRACT(ReferenceAttribute, AttributeVector);

}

namespace vespalib::datastore {

using Reference = search::attribute::Reference;

template class UniqueStoreAllocator<Reference, EntryRefT<22>>;
template class UniqueStore<Reference, EntryRefT<22>>;
template class UniqueStoreBuilder<UniqueStoreAllocator<Reference, EntryRefT<22>>>;
template class UniqueStoreEnumerator<EntryRefT<22>>;

}