public boolean resolveConflict(IIndex writeSet, ITuple txTuple, ITuple currentTuple)
        throws Exception {

      // The key must be the same for both tuples.
      assertEquals(txTuple.getKey(), currentTuple.getKey());

      // the key for the conflicting writes.
      final byte[] key = txTuple.getKey();

      assertEquals("key", expectedKey, key);

      writeSet.insert(key, resolvedValue);

      return true;
    }
  /**
   * Creates a {@link Justification}, writes it on the store using {@link
   * RDFJoinNexus#newInsertBuffer(IMutableRelation)}, verifies that we can read it back from the
   * store, and then retracts the justified statement and verifies that the justification was also
   * retracted.
   */
  public void test_writeReadRetract() {

    final Properties properties = super.getProperties();

    // override the default axiom model.
    properties.setProperty(
        com.bigdata.rdf.store.AbstractTripleStore.Options.AXIOMS_CLASS, NoAxioms.class.getName());

    final AbstractTripleStore store = getStore(properties);

    try {

      if (!store.isJustify()) {

        log.warn("Test skipped - justifications not enabled");
      }

      /*
       * the explicit statement that is the support for the rule.
       */

      final IV U = store.addTerm(new URIImpl("http://www.bigdata.com/U"));
      final IV A = store.addTerm(new URIImpl("http://www.bigdata.com/A"));
      final IV Y = store.addTerm(new URIImpl("http://www.bigdata.com/Y"));

      store.addStatements(
          new SPO[] { //
            new SPO(U, A, Y, StatementEnum.Explicit) //
          }, //
          1);

      assertTrue(store.hasStatement(U, A, Y));
      assertEquals(1, store.getStatementCount());

      final InferenceEngine inf = store.getInferenceEngine();

      final Vocabulary vocab = store.getVocabulary();

      // the rule.
      final Rule rule = new RuleRdf01(store.getSPORelation().getNamespace(), vocab);

      final IJoinNexus joinNexus =
          store
              .newJoinNexusFactory(
                  RuleContextEnum.DatabaseAtOnceClosure,
                  ActionEnum.Insert,
                  IJoinNexus.ALL,
                  null /* filter */)
              .newInstance(store.getIndexManager());

      /*
       * The buffer that accepts solutions and causes them to be written
       * onto the statement indices and the justifications index.
       */
      final IBuffer<ISolution[]> insertBuffer = joinNexus.newInsertBuffer(store.getSPORelation());

      // the expected justification (setup and verified below).
      final Justification jst;

      // the expected entailment.
      final SPO expectedEntailment =
          new SPO( //
              A, vocab.get(RDF.TYPE), vocab.get(RDF.PROPERTY), StatementEnum.Inferred);

      {
        final IBindingSet bindingSet = joinNexus.newBindingSet(rule);

        /*
         * Note: rdfs1 is implemented using a distinct term scan. This
         * has the effect of leaving the variables that do not appear in
         * the head of the rule unbound. Therefore we DO NOT bind those
         * variables here in the test case and they will be represented
         * as ZERO (0L) in the justifications index and interpreted as
         * wildcards.
         */
        //                bindingSet.set(Var.var("u"), new Constant<IV>(U));
        bindingSet.set(Var.var("a"), new Constant<IV>(A));
        //                bindingSet.set(Var.var("y"), new Constant<IV>(Y));

        final ISolution solution = new Solution(joinNexus, rule, bindingSet);

        /*
         * Verify the justification that will be built from that
         * solution.
         */
        {
          jst = new Justification(solution);

          /*
           * Verify the bindings on the head of the rule as
           * represented by the justification.
           */
          assertEquals(expectedEntailment, jst.getHead());

          /*
           * Verify the bindings on the tail of the rule as
           * represented by the justification. Again, note that the
           * variables that do not appear in the head of the rule are
           * left unbound for rdfs1 as a side-effect of evaluation
           * using a distinct term scan.
           */
          final SPO[] expectedTail =
              new SPO[] { //
                new SPO(NULL, A, NULL, StatementEnum.Inferred) //
              };

          if (!Arrays.equals(expectedTail, jst.getTail())) {

            fail("Expected: " + Arrays.toString(expectedTail) + ", but actual: " + jst);
          }
        }

        // insert solution into the buffer.
        insertBuffer.add(new ISolution[] {solution});
      }

      //            SPOAssertionBuffer buf = new SPOAssertionBuffer(store, store,
      //                    null/* filter */, 100/* capacity */, true/* justified */);
      //
      //            assertTrue(buf.add(head, jst));

      // no justifications before hand.
      assertEquals(0L, store.getSPORelation().getJustificationIndex().rangeCount());

      // flush the buffer.
      assertEquals(1L, insertBuffer.flush());

      // one justification afterwards.
      assertEquals(1L, store.getSPORelation().getJustificationIndex().rangeCount());

      /*
       * verify read back from the index.
       */
      {
        final ITupleIterator<Justification> itr =
            store.getSPORelation().getJustificationIndex().rangeIterator();

        while (itr.hasNext()) {

          final ITuple<Justification> tuple = itr.next();

          // de-serialize the justification from the key.
          final Justification tmp = tuple.getObject();

          // verify the same.
          assertEquals(jst, tmp);

          // no more justifications in the index.
          assertFalse(itr.hasNext());
        }
      }

      /*
       * test iterator with a single justification.
       */
      {
        final FullyBufferedJustificationIterator itr =
            new FullyBufferedJustificationIterator(store, expectedEntailment);

        assertTrue(itr.hasNext());

        final Justification tmp = itr.next();

        assertEquals(jst, tmp);
      }

      // an empty focusStore.
      final TempTripleStore focusStore =
          new TempTripleStore(store.getIndexManager().getTempStore(), store.getProperties(), store);

      try {

        /*
         * The inference (A rdf:type rdf:property) is grounded by the
         * explicit statement (U A Y).
         */

        assertTrue(
            Justification.isGrounded(
                inf,
                focusStore,
                store,
                expectedEntailment,
                false /* testHead */,
                true /* testFocusStore */,
                new VisitedSPOSet(focusStore.getIndexManager())));

        // add the statement (U A Y) to the focusStore.
        focusStore.addStatements(
            new SPO[] { //
              new SPO(U, A, Y, StatementEnum.Explicit) //
            }, //
            1);

        /*
         * The inference is no longer grounded since we have declared
         * that we are also retracting its grounds.
         */
        assertFalse(
            Justification.isGrounded(
                inf,
                focusStore,
                store,
                expectedEntailment,
                false /* testHead */,
                true /* testFocusStore */,
                new VisitedSPOSet(focusStore.getIndexManager())));

      } finally {

        /*
         * Destroy the temp kb, but not the backing TemporaryStore. That
         * will be destroyed when we destroy the IndexManager associated
         * with the main store (below).
         */
        focusStore.destroy();
      }

      /*
       * remove the justified statements.
       */

      assertEquals(
          1L,
          store
              .getAccessPath(expectedEntailment.s, expectedEntailment.p, expectedEntailment.o)
              .removeAll());

      /*
       * verify that the justification for that statement is gone.
       */
      {
        final ITupleIterator<?> itr =
            store.getSPORelation().getJustificationIndex().rangeIterator();

        assertFalse(itr.hasNext());
      }

    } finally {

      store.__tearDownUnitTest();
    }
  }
Beispiel #3
0
  /**
   * Set the direction of iterator progress. Clears {@link #sourceTuple} iff the current direction
   * is different from the new direction and is otherwise a NOP.
   *
   * <p>Note: Care is required for sequences such as
   *
   * <pre>
   * ITuple t1 = next();
   *
   * ITuple t2 = prior();
   * </pre>
   *
   * <p>to visit the same tuple for {@link #next()} and {@link #prior()}.
   *
   * @param forward <code>true</code> iff the new direction of iterator progress is forward using
   *     {@link #hasNext()} and {@link #next()}.
   */
  private void setForwardDirection(boolean forward) {

    if (this.forward != forward) {

      if (INFO) log.info("Changing direction: forward=" + forward);

      /*
       * This is the last key visited -or- null iff nothing has been
       * visited.
       */
      final byte[] lastKeyVisited;
      if (lastVisited == -1) {

        lastKeyVisited = null;

      } else {

        //                lastKeyVisited = ((ITupleCursor2<E>) sourceIterator[lastVisited])
        //                        .tuple().getKey();
        lastKeyVisited = lastKeyBuffer.getKey();

        if (INFO) log.info("key for last tuple visited=" + BytesUtil.toString(lastKeyVisited));
      }

      for (int i = 0; i < n; i++) {

        /*
         * Recover the _current_ tuple for each source iterator.
         */

        // current tuple for the source iterator.
        ITuple<E> tuple = ((ITupleCursor2<E>) sourceIterator[i]).tuple();

        if (INFO) log.info("sourceIterator[" + i + "]=" + tuple);

        if (lastKeyVisited != null) {

          /*
           * When we are changing to [forward == true] (visiting the
           * next tuples in the index order), then we advance the
           * source iterator zero or more tuples until it is
           * positioned GT the lastVisitedKey.
           *
           * When we are changing to [forward == false] (visiting the
           * prior tuples in the index order), then we backup the
           * source iterator zero or more tuples until it is
           * positioned LT the lastVisitedKey.
           */

          while (tuple != null) {

            final int ret =
                BytesUtil.compareBytes( //
                    tuple.getKey(), //
                    lastKeyVisited //
                    );

            final boolean ok = forward ? ret > 0 : ret < 0;

            if (ok) break;

            /*
             * If the source iterator is currently positioned on the
             * same key as the last tuple that we visited then we
             * need to move it off of that key - either to the
             * previous or the next visitable tuple depending on the
             * new direction for the iterator.
             */

            if (forward) {

              if (sourceIterator[i].hasNext()) {

                // next tuple
                tuple = sourceIterator[i].next();

              } else {

                // exhausted in this direction.
                tuple = null;
              }

            } else {

              if (sourceIterator[i].hasPrior()) {

                // prior tuple
                tuple = sourceIterator[i].prior();

              } else {

                // exhausted in this direction.
                tuple = null;
              }
            }

            if (INFO)
              log.info(
                  "skipping tuple: source="
                      + i
                      + ", direction="
                      + (forward ? "next" : "prior")
                      + ", newTuple="
                      + tuple);
          }
        }

        sourceTuple[i] = tuple;

        // as assigned to source[i].
        if (INFO) log.info("sourceTuple   [" + i + "]=" + sourceTuple[i]);
      }

      // set the new iterator direction.
      this.forward = forward;

      // clear current since the old lookahead choice is no longer valid.
      this.current = -1;
    }
  }