Search in sources :

Example 1 with TaskContext

use of io.prestosql.operator.TaskContext in project hetu-core by openlookeng.

the class TestDynamicFiltersCollector method TestCollectingGlobalDynamicFilters.

@Test
public void TestCollectingGlobalDynamicFilters() throws InterruptedException {
    final QueryId queryId = new QueryId("test_query");
    final String filterId = "1";
    final String columnName = "column";
    final TestingColumnHandle columnHandle = new TestingColumnHandle(columnName);
    final Set<String> valueSet = ImmutableSet.of("1", "2", "3");
    TaskContext taskContext = mock(TaskContext.class);
    Session session = testSessionBuilder().setQueryId(queryId).setSystemProperty(ENABLE_DYNAMIC_FILTERING, "true").setSystemProperty(DYNAMIC_FILTERING_DATA_TYPE, "HASHSET").build();
    when(taskContext.getSession()).thenReturn(session);
    // set up state store and merged dynamic filters map
    Map mockMap = new HashMap<>();
    StateStoreProvider stateStoreProvider = mock(StateStoreProvider.class);
    StateStore stateStore = mock(StateStore.class);
    StateMap stateMap = new MockStateMap<>("test-map", mockMap);
    when(stateStoreProvider.getStateStore()).thenReturn(stateStore);
    when(stateStore.getStateCollection(any())).thenReturn(stateMap);
    when(stateStore.createStateMap(any())).thenReturn(stateMap);
    when(stateStore.getOrCreateStateCollection(any(), any())).thenReturn(stateMap);
    // set up state store listener and dynamic filter cache
    StateStoreListenerManager stateStoreListenerManager = new StateStoreListenerManager(stateStoreProvider);
    DynamicFilterCacheManager dynamicFilterCacheManager = new DynamicFilterCacheManager();
    stateStoreListenerManager.addStateStoreListener(new DynamicFilterListener(dynamicFilterCacheManager), MERGED_DYNAMIC_FILTERS);
    LocalDynamicFiltersCollector collector = new LocalDynamicFiltersCollector(taskContext, Optional.empty(), dynamicFilterCacheManager);
    TableScanNode tableScan = mock(TableScanNode.class);
    when(tableScan.getAssignments()).thenReturn(ImmutableMap.of(new Symbol(columnName), columnHandle));
    List<DynamicFilters.Descriptor> dynamicFilterDescriptors = ImmutableList.of(new DynamicFilters.Descriptor(filterId, new VariableReferenceExpression(columnName, BIGINT)));
    collector.initContext(ImmutableList.of(dynamicFilterDescriptors), SymbolUtils.toLayOut(tableScan.getOutputSymbols()));
    assertTrue(collector.getDynamicFilters(tableScan).isEmpty(), "there should be no dynamic filter available");
    // put some values in state store as a new dynamic filter
    // and wait for the listener to process the event
    stateMap.put(createKey(DynamicFilterUtils.FILTERPREFIX, filterId, queryId.getId()), valueSet);
    TimeUnit.MILLISECONDS.sleep(100);
    // get available dynamic filter and verify it
    List<Map<ColumnHandle, DynamicFilter>> dynamicFilters = collector.getDynamicFilters(tableScan);
    assertEquals(dynamicFilters.size(), 1, "there should be a new dynamic filter");
    assertEquals(dynamicFilters.size(), 1);
    DynamicFilter dynamicFilter = dynamicFilters.get(0).get(columnHandle);
    assertTrue(dynamicFilter instanceof HashSetDynamicFilter, "new dynamic filter should be hashset");
    assertEquals(dynamicFilter.getSize(), valueSet.size(), "new dynamic filter should have correct size");
    for (String value : valueSet) {
        assertTrue(dynamicFilter.contains(value), "new dynamic filter should contain correct values");
    }
    // clean up when task finishes
    collector.removeDynamicFilter(true);
    DynamicFilter cachedFilter = dynamicFilterCacheManager.getDynamicFilter(DynamicFilterCacheManager.createCacheKey(filterId, queryId.getId()));
    assertNull(cachedFilter, "cached dynamic filter should have been removed");
}
Also used : HashMap(java.util.HashMap) Symbol(io.prestosql.spi.plan.Symbol) MockStateMap(io.prestosql.statestore.MockStateMap) StateMap(io.prestosql.spi.statestore.StateMap) StateStoreListenerManager(io.prestosql.statestore.listener.StateStoreListenerManager) StateStoreProvider(io.prestosql.statestore.StateStoreProvider) MockStateMap(io.prestosql.statestore.MockStateMap) TestingColumnHandle(io.prestosql.spi.connector.TestingColumnHandle) DynamicFilters(io.prestosql.sql.DynamicFilters) DynamicFilterListener(io.prestosql.dynamicfilter.DynamicFilterListener) DynamicFilterCacheManager(io.prestosql.dynamicfilter.DynamicFilterCacheManager) TaskContext(io.prestosql.operator.TaskContext) DynamicFilter(io.prestosql.spi.dynamicfilter.DynamicFilter) HashSetDynamicFilter(io.prestosql.spi.dynamicfilter.HashSetDynamicFilter) QueryId(io.prestosql.spi.QueryId) StateStore(io.prestosql.spi.statestore.StateStore) HashSetDynamicFilter(io.prestosql.spi.dynamicfilter.HashSetDynamicFilter) TableScanNode(io.prestosql.spi.plan.TableScanNode) VariableReferenceExpression(io.prestosql.spi.relation.VariableReferenceExpression) MockStateMap(io.prestosql.statestore.MockStateMap) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) StateMap(io.prestosql.spi.statestore.StateMap) Session(io.prestosql.Session) Test(org.testng.annotations.Test)

Example 2 with TaskContext

use of io.prestosql.operator.TaskContext in project hetu-core by openlookeng.

the class LocalQueryRunner method executeInternal.

private MaterializedResultWithPlan executeInternal(Session session, @Language("SQL") String sql) {
    lock.readLock().lock();
    try (Closer closer = Closer.create()) {
        AtomicReference<MaterializedResult.Builder> builder = new AtomicReference<>();
        PageConsumerOutputFactory outputFactory = new PageConsumerOutputFactory(types -> {
            builder.compareAndSet(null, MaterializedResult.resultBuilder(session, types));
            return builder.get()::page;
        });
        TaskContext taskContext = TestingTaskContext.builder(notificationExecutor, yieldExecutor, session).setMaxSpillSize(nodeSpillConfig.getMaxSpillPerNode()).setQueryMaxSpillSize(nodeSpillConfig.getQueryMaxSpillPerNode()).build();
        Plan plan = createPlan(session, sql, WarningCollector.NOOP);
        List<Driver> drivers = createDrivers(session, plan, outputFactory, taskContext);
        drivers.forEach(closer::register);
        boolean done = false;
        while (!done) {
            boolean processed = false;
            for (Driver driver : drivers) {
                if (alwaysRevokeMemory) {
                    driver.getDriverContext().getOperatorContexts().stream().filter(operatorContext -> operatorContext.getOperatorStats().getRevocableMemoryReservation().getValue() > 0).forEach(OperatorContext::requestMemoryRevoking);
                }
                if (!driver.isFinished()) {
                    driver.process();
                    processed = true;
                }
            }
            done = !processed;
        }
        verify(builder.get() != null, "Output operator was not created");
        return new MaterializedResultWithPlan(builder.get().build(), plan);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        lock.readLock().unlock();
    }
}
Also used : Closer(com.google.common.io.Closer) CostCalculatorWithEstimatedExchanges(io.prestosql.cost.CostCalculatorWithEstimatedExchanges) RollbackTask(io.prestosql.execution.RollbackTask) FilterStatsCalculator(io.prestosql.cost.FilterStatsCalculator) Plan(io.prestosql.sql.planner.Plan) ConnectorManager(io.prestosql.connector.ConnectorManager) HttpServerConfig(io.airlift.http.server.HttpServerConfig) TypeAnalyzer(io.prestosql.sql.planner.TypeAnalyzer) Prepare(io.prestosql.sql.tree.Prepare) Statement(io.prestosql.sql.tree.Statement) WarningCollector(io.prestosql.execution.warnings.WarningCollector) SnapshotConfig(io.prestosql.snapshot.SnapshotConfig) SchemaPropertiesSystemTable(io.prestosql.connector.system.SchemaPropertiesSystemTable) NoOpResourceGroupManager(io.prestosql.execution.resourcegroups.NoOpResourceGroupManager) PlanSanityChecker(io.prestosql.sql.planner.sanity.PlanSanityChecker) Map(java.util.Map) TestingSession.createBogusTestingCatalog(io.prestosql.testing.TestingSession.createBogusTestingCatalog) TransactionBuilder.transaction(io.prestosql.transaction.TransactionBuilder.transaction) GlobalSystemConnector(io.prestosql.connector.system.GlobalSystemConnector) RenameColumn(io.prestosql.sql.tree.RenameColumn) HeuristicIndexerManager(io.prestosql.heuristicindex.HeuristicIndexerManager) PlanNodeId(io.prestosql.spi.plan.PlanNodeId) TransactionManagerConfig(io.prestosql.transaction.TransactionManagerConfig) RowExpressionDeterminismEvaluator(io.prestosql.sql.relational.RowExpressionDeterminismEvaluator) SetSessionTask(io.prestosql.execution.SetSessionTask) CostCalculatorUsingExchanges(io.prestosql.cost.CostCalculatorUsingExchanges) PageConsumerOutputFactory(io.prestosql.testing.PageConsumerOperator.PageConsumerOutputFactory) CommentTask(io.prestosql.execution.CommentTask) PlanNode(io.prestosql.spi.plan.PlanNode) NodeSchedulerConfig(io.prestosql.execution.scheduler.NodeSchedulerConfig) RowExpressionDomainTranslator(io.prestosql.sql.relational.RowExpressionDomainTranslator) ReuseExchangeOperator(io.prestosql.spi.operator.ReuseExchangeOperator) DropView(io.prestosql.sql.tree.DropView) PageSinkManager(io.prestosql.split.PageSinkManager) QueryPreparer(io.prestosql.execution.QueryPreparer) TaskManagerConfig(io.prestosql.execution.TaskManagerConfig) Plugin(io.prestosql.spi.Plugin) LocalExecutionPlanner(io.prestosql.sql.planner.LocalExecutionPlanner) EmbedVersion(io.prestosql.version.EmbedVersion) DropTable(io.prestosql.sql.tree.DropTable) TransactionManager(io.prestosql.transaction.TransactionManager) StageExecutionDescriptor(io.prestosql.operator.StageExecutionDescriptor) TaskContext(io.prestosql.operator.TaskContext) PlanPrinter(io.prestosql.sql.planner.planprinter.PlanPrinter) IndexJoinLookupStats(io.prestosql.operator.index.IndexJoinLookupStats) CommitTask(io.prestosql.execution.CommitTask) GenericSpillerFactory(io.prestosql.spiller.GenericSpillerFactory) ResetSession(io.prestosql.sql.tree.ResetSession) QualifiedObjectName(io.prestosql.spi.connector.QualifiedObjectName) Deallocate(io.prestosql.sql.tree.Deallocate) ResetSessionTask(io.prestosql.execution.ResetSessionTask) MetadataUtil(io.prestosql.metadata.MetadataUtil) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ParsingUtil.createParsingOptions(io.prestosql.sql.ParsingUtil.createParsingOptions) NodeTaskMap(io.prestosql.execution.NodeTaskMap) SplitSource(io.prestosql.split.SplitSource) Comment(io.prestosql.sql.tree.Comment) SpillerFactory(io.prestosql.spiller.SpillerFactory) RenameTable(io.prestosql.sql.tree.RenameTable) DriverContext(io.prestosql.operator.DriverContext) TaskCountEstimator(io.prestosql.cost.TaskCountEstimator) Lifespan(io.prestosql.execution.Lifespan) StatsCalculatorModule.createNewStatsCalculator(io.prestosql.cost.StatsCalculatorModule.createNewStatsCalculator) CreateViewTask(io.prestosql.execution.CreateViewTask) IOException(java.io.IOException) GlobalSystemConnectorFactory(io.prestosql.connector.system.GlobalSystemConnectorFactory) DeallocateTask(io.prestosql.execution.DeallocateTask) CatalogManager(io.prestosql.metadata.CatalogManager) PlanOptimizer(io.prestosql.sql.planner.optimizations.PlanOptimizer) QueryExplainer(io.prestosql.sql.analyzer.QueryExplainer) SystemSessionProperties(io.prestosql.SystemSessionProperties) SqlParser(io.prestosql.sql.parser.SqlParser) QueryManagerConfig(io.prestosql.execution.QueryManagerConfig) Duration(io.airlift.units.Duration) TaskSource(io.prestosql.execution.TaskSource) HetuConfig(io.prestosql.utils.HetuConfig) ConnectorPlanOptimizerManager(io.prestosql.sql.planner.ConnectorPlanOptimizerManager) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) SetPathTask(io.prestosql.execution.SetPathTask) StartTransaction(io.prestosql.sql.tree.StartTransaction) Type(io.prestosql.spi.type.Type) StatsCalculator(io.prestosql.cost.StatsCalculator) PartitioningSpillerFactory(io.prestosql.spiller.PartitioningSpillerFactory) ImmutableSet(com.google.common.collect.ImmutableSet) CatalogName(io.prestosql.spi.connector.CatalogName) GenericPartitioningSpillerFactory(io.prestosql.spiller.GenericPartitioningSpillerFactory) Rollback(io.prestosql.sql.tree.Rollback) RenameColumnTask(io.prestosql.execution.RenameColumnTask) NodePartitioningManager(io.prestosql.sql.planner.NodePartitioningManager) NOT_PARTITIONED(io.prestosql.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED) Split(io.prestosql.metadata.Split) TableHandle(io.prestosql.spi.metadata.TableHandle) Function(java.util.function.Function) DynamicFilterCacheManager(io.prestosql.dynamicfilter.DynamicFilterCacheManager) LookupJoinOperators(io.prestosql.operator.LookupJoinOperators) PlanOptimizers(io.prestosql.sql.planner.PlanOptimizers) ImmutableList(com.google.common.collect.ImmutableList) LocalStateStoreProvider(io.prestosql.statestore.LocalStateStoreProvider) PagesIndexPageSorter(io.prestosql.PagesIndexPageSorter) ExecutorService(java.util.concurrent.ExecutorService) IndexManager(io.prestosql.index.IndexManager) RenameIndex(io.prestosql.sql.tree.RenameIndex) PlanNodeSearcher.searchFrom(io.prestosql.sql.planner.optimizations.PlanNodeSearcher.searchFrom) StateStoreProvider(io.prestosql.statestore.StateStoreProvider) PlanNodeIdAllocator(io.prestosql.spi.plan.PlanNodeIdAllocator) JoinCompiler(io.prestosql.sql.gen.JoinCompiler) SpillerStats(io.prestosql.spiller.SpillerStats) GROUPED_SCHEDULING(io.prestosql.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.GROUPED_SCHEDULING) InternalCommunicationConfig(io.prestosql.server.InternalCommunicationConfig) CostCalculator(io.prestosql.cost.CostCalculator) SubPlan(io.prestosql.sql.planner.SubPlan) NodeInfo(io.airlift.node.NodeInfo) RenameIndexTask(io.prestosql.execution.RenameIndexTask) NodeSystemTable(io.prestosql.connector.system.NodeSystemTable) StateStoreListenerManager(io.prestosql.statestore.listener.StateStoreListenerManager) CreateTable(io.prestosql.sql.tree.CreateTable) Executors.newScheduledThreadPool(java.util.concurrent.Executors.newScheduledThreadPool) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) EventListenerManager(io.prestosql.eventlistener.EventListenerManager) PageIndexerFactory(io.prestosql.spi.PageIndexerFactory) OrderingCompiler(io.prestosql.sql.gen.OrderingCompiler) UNGROUPED_SCHEDULING(io.prestosql.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING) SchemaPropertyManager(io.prestosql.metadata.SchemaPropertyManager) FileSingleStreamSpillerFactory(io.prestosql.spiller.FileSingleStreamSpillerFactory) TableScanNode(io.prestosql.spi.plan.TableScanNode) TablePropertiesSystemTable(io.prestosql.connector.system.TablePropertiesSystemTable) Metadata(io.prestosql.metadata.Metadata) MetadataManager(io.prestosql.metadata.MetadataManager) LogicalPlanner(io.prestosql.sql.planner.LogicalPlanner) SetSession(io.prestosql.sql.tree.SetSession) UncheckedIOException(java.io.UncheckedIOException) HttpServerInfo(io.airlift.http.server.HttpServerInfo) CreateView(io.prestosql.sql.tree.CreateView) CatalogSystemTable(io.prestosql.connector.system.CatalogSystemTable) Driver(io.prestosql.operator.Driver) PluginManager(io.prestosql.server.PluginManager) PreparedQuery(io.prestosql.execution.QueryPreparer.PreparedQuery) StartTransactionTask(io.prestosql.execution.StartTransactionTask) ExpressionCompiler(io.prestosql.sql.gen.ExpressionCompiler) SetPath(io.prestosql.sql.tree.SetPath) TESTING_CATALOG(io.prestosql.testing.TestingSession.TESTING_CATALOG) DropTableTask(io.prestosql.execution.DropTableTask) DataDefinitionTask(io.prestosql.execution.DataDefinitionTask) NodeScheduler(io.prestosql.execution.scheduler.NodeScheduler) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) InMemoryTransactionManager(io.prestosql.transaction.InMemoryTransactionManager) ArrayList(java.util.ArrayList) CatalogConnectorStore(io.prestosql.connector.CatalogConnectorStore) GroupByHashPageIndexerFactory(io.prestosql.GroupByHashPageIndexerFactory) SeedStoreManager(io.prestosql.seedstore.SeedStoreManager) Closer(com.google.common.io.Closer) InMemoryNodeManager(io.prestosql.metadata.InMemoryNodeManager) EmbeddedStateStoreLauncher(io.prestosql.statestore.EmbeddedStateStoreLauncher) Session(io.prestosql.Session) PageSourceManager(io.prestosql.split.PageSourceManager) ScheduledSplit(io.prestosql.execution.ScheduledSplit) SessionPropertyDefaults(io.prestosql.server.SessionPropertyDefaults) TransactionsSystemTable(io.prestosql.connector.system.TransactionsSystemTable) Language(org.intellij.lang.annotations.Language) MoreFutures.getFutureValue(io.airlift.concurrent.MoreFutures.getFutureValue) CostComparator(io.prestosql.cost.CostComparator) FinalizerService(io.prestosql.util.FinalizerService) CubeManager(io.prestosql.cube.CubeManager) Lock(java.util.concurrent.locks.Lock) JoinFilterFunctionCompiler(io.prestosql.sql.gen.JoinFilterFunctionCompiler) TreeAssertions.assertFormattedSql(io.prestosql.sql.testing.TreeAssertions.assertFormattedSql) HandleResolver(io.prestosql.metadata.HandleResolver) ConnectorFactory(io.prestosql.spi.connector.ConnectorFactory) SplitManager(io.prestosql.split.SplitManager) QualifiedTablePrefix(io.prestosql.metadata.QualifiedTablePrefix) TablePropertyManager(io.prestosql.metadata.TablePropertyManager) TestingMBeanServer(org.weakref.jmx.testing.TestingMBeanServer) StatsNormalizer(io.prestosql.cost.StatsNormalizer) FileSystemClientManager(io.prestosql.filesystem.FileSystemClientManager) Kryo(com.esotericsoftware.kryo.Kryo) AnalyzePropertiesSystemTable(io.prestosql.connector.system.AnalyzePropertiesSystemTable) ServerConfig(io.prestosql.server.ServerConfig) ColumnPropertyManager(io.prestosql.metadata.ColumnPropertyManager) PageFunctionCompiler(io.prestosql.sql.gen.PageFunctionCompiler) Commit(io.prestosql.sql.tree.Commit) ImmutableMap(com.google.common.collect.ImmutableMap) OutputFactory(io.prestosql.operator.OutputFactory) Preconditions.checkState(com.google.common.base.Preconditions.checkState) PluginManagerConfig(io.prestosql.server.PluginManagerConfig) List(java.util.List) ColumnPropertiesSystemTable(io.prestosql.connector.system.ColumnPropertiesSystemTable) TableCommentSystemTable(io.prestosql.connector.system.TableCommentSystemTable) SessionPropertyManager(io.prestosql.metadata.SessionPropertyManager) Optional(java.util.Optional) Analysis(io.prestosql.sql.analyzer.Analysis) NodeSpillConfig(io.prestosql.spiller.NodeSpillConfig) FunctionAndTypeManager(io.prestosql.metadata.FunctionAndTypeManager) MemoryManagerConfig(io.prestosql.memory.MemoryManagerConfig) LegacyNetworkTopology(io.prestosql.execution.scheduler.LegacyNetworkTopology) CreateTableTask(io.prestosql.execution.CreateTableTask) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) PlanFragmenter(io.prestosql.sql.planner.PlanFragmenter) DropViewTask(io.prestosql.execution.DropViewTask) PrepareTask(io.prestosql.execution.PrepareTask) Verify.verify(com.google.common.base.Verify.verify) Threads.daemonThreadsNamed(io.airlift.concurrent.Threads.daemonThreadsNamed) Objects.requireNonNull(java.util.Objects.requireNonNull) PasswordAuthenticatorManager(io.prestosql.server.security.PasswordAuthenticatorManager) PagesIndex(io.prestosql.operator.PagesIndex) ScalarStatsCalculator(io.prestosql.cost.ScalarStatsCalculator) OperatorContext(io.prestosql.operator.OperatorContext) DriverFactory(io.prestosql.operator.DriverFactory) AnalyzePropertyManager(io.prestosql.metadata.AnalyzePropertyManager) GroupProviderManager(io.prestosql.security.GroupProviderManager) PageSorter(io.prestosql.spi.PageSorter) LocalExecutionPlan(io.prestosql.sql.planner.LocalExecutionPlanner.LocalExecutionPlan) Analyzer(io.prestosql.sql.analyzer.Analyzer) TimeUnit(java.util.concurrent.TimeUnit) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) HetuMetaStoreManager(io.prestosql.metastore.HetuMetaStoreManager) FeaturesConfig(io.prestosql.sql.analyzer.FeaturesConfig) RenameTableTask(io.prestosql.execution.RenameTableTask) MBeanExporter(org.weakref.jmx.MBeanExporter) Collections(java.util.Collections) TaskContext(io.prestosql.operator.TaskContext) PageConsumerOutputFactory(io.prestosql.testing.PageConsumerOperator.PageConsumerOutputFactory) Driver(io.prestosql.operator.Driver) AtomicReference(java.util.concurrent.atomic.AtomicReference) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Plan(io.prestosql.sql.planner.Plan) SubPlan(io.prestosql.sql.planner.SubPlan) LocalExecutionPlan(io.prestosql.sql.planner.LocalExecutionPlanner.LocalExecutionPlan) OperatorContext(io.prestosql.operator.OperatorContext)

Example 3 with TaskContext

use of io.prestosql.operator.TaskContext in project hetu-core by openlookeng.

the class TestingTaskContext method createTaskContext.

private static TaskContext createTaskContext(QueryContext queryContext, Session session, TaskStateMachine taskStateMachine) {
    TaskContext taskContext = queryContext.addTaskContext(taskStateMachine, session, true, true, OptionalInt.empty(), Optional.empty(), TESTING_SERDE_FACTORY);
    taskContext.getSnapshotManager().setTotalComponents(100);
    return taskContext;
}
Also used : TaskContext(io.prestosql.operator.TaskContext)

Example 4 with TaskContext

use of io.prestosql.operator.TaskContext in project hetu-core by openlookeng.

the class MemoryLocalQueryRunner method execute.

public List<Page> execute(@Language("SQL") String query) {
    MemoryPool memoryPool = new MemoryPool(new MemoryPoolId("test"), new DataSize(2, GIGABYTE));
    SpillSpaceTracker spillSpaceTracker = new SpillSpaceTracker(new DataSize(1, GIGABYTE));
    QueryContext queryContext = new QueryContext(new QueryId("test"), new DataSize(1, GIGABYTE), new DataSize(2, GIGABYTE), memoryPool, new TestingGcMonitor(), localQueryRunner.getExecutor(), localQueryRunner.getScheduler(), new DataSize(4, GIGABYTE), spillSpaceTracker, NOOP_SNAPSHOT_UTILS);
    TaskContext taskContext = queryContext.addTaskContext(new TaskStateMachine(new TaskId("query", 0, 0), localQueryRunner.getExecutor()), localQueryRunner.getDefaultSession(), false, false, OptionalInt.empty(), Optional.empty(), TESTING_SERDE_FACTORY);
    // Use NullOutputFactory to avoid coping out results to avoid affecting benchmark results
    ImmutableList.Builder<Page> output = ImmutableList.builder();
    List<Driver> drivers = localQueryRunner.createDrivers(query, new PageConsumerOperator.PageConsumerOutputFactory(types -> output::add), taskContext);
    boolean done = false;
    while (!done) {
        boolean processed = false;
        for (Driver driver : drivers) {
            if (!driver.isFinished()) {
                driver.process();
                processed = true;
            }
        }
        done = !processed;
    }
    return output.build();
}
Also used : TESTING_SERDE_FACTORY(io.prestosql.testing.TestingPagesSerdeFactory.TESTING_SERDE_FACTORY) TaskId(io.prestosql.execution.TaskId) TaskStateMachine(io.prestosql.execution.TaskStateMachine) Plugin(io.prestosql.spi.Plugin) TpchConnectorFactory(io.prestosql.plugin.tpch.TpchConnectorFactory) SpillSpaceTracker(io.prestosql.spiller.SpillSpaceTracker) TaskContext(io.prestosql.operator.TaskContext) TableHandle(io.prestosql.spi.metadata.TableHandle) OptionalInt(java.util.OptionalInt) MemoryPool(io.prestosql.memory.MemoryPool) QualifiedObjectName(io.prestosql.spi.connector.QualifiedObjectName) TestingSession.testSessionBuilder(io.prestosql.testing.TestingSession.testSessionBuilder) GIGABYTE(io.airlift.units.DataSize.Unit.GIGABYTE) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Session(io.prestosql.Session) QueryId(io.prestosql.spi.QueryId) PageConsumerOperator(io.prestosql.testing.PageConsumerOperator) ImmutableMap(com.google.common.collect.ImmutableMap) Language(org.intellij.lang.annotations.Language) NOOP_SNAPSHOT_UTILS(io.prestosql.testing.TestingSnapshotUtils.NOOP_SNAPSHOT_UTILS) Page(io.prestosql.spi.Page) QueryContext(io.prestosql.memory.QueryContext) MemoryConnectorFactory(io.prestosql.plugin.memory.MemoryConnectorFactory) MemoryPoolId(io.prestosql.spi.memory.MemoryPoolId) Metadata(io.prestosql.metadata.Metadata) DataSize(io.airlift.units.DataSize) LocalQueryRunner(io.prestosql.testing.LocalQueryRunner) List(java.util.List) Driver(io.prestosql.operator.Driver) Optional(java.util.Optional) Assert.assertTrue(org.testng.Assert.assertTrue) TestingGcMonitor(io.airlift.stats.TestingGcMonitor) SpillSpaceTracker(io.prestosql.spiller.SpillSpaceTracker) TaskContext(io.prestosql.operator.TaskContext) TaskId(io.prestosql.execution.TaskId) ImmutableList(com.google.common.collect.ImmutableList) QueryId(io.prestosql.spi.QueryId) Driver(io.prestosql.operator.Driver) Page(io.prestosql.spi.Page) QueryContext(io.prestosql.memory.QueryContext) TaskStateMachine(io.prestosql.execution.TaskStateMachine) PageConsumerOperator(io.prestosql.testing.PageConsumerOperator) DataSize(io.airlift.units.DataSize) TestingGcMonitor(io.airlift.stats.TestingGcMonitor) MemoryPoolId(io.prestosql.spi.memory.MemoryPoolId) MemoryPool(io.prestosql.memory.MemoryPool)

Example 5 with TaskContext

use of io.prestosql.operator.TaskContext in project hetu-core by openlookeng.

the class TestPartitionedOutputBuffer method testMarkers.

@Test
public void testMarkers() {
    int firstPartition = 0;
    int secondPartition = 1;
    PartitionedOutputBuffer buffer = createPartitionedBuffer(createInitialEmptyOutputBuffers(PARTITIONED).withBuffer(FIRST, firstPartition).withBuffer(SECOND, secondPartition).withNoMoreBufferIds(), sizeOfPages(6));
    ScheduledExecutorService scheduler = newScheduledThreadPool(4, daemonThreadsNamed("test-%s"));
    ScheduledExecutorService scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s"));
    TaskContext taskContext = createTaskContext(scheduler, scheduledExecutor, TEST_SNAPSHOT_SESSION);
    buffer.setTaskContext(taskContext);
    buffer.addInputChannel("id");
    buffer.setNoMoreInputChannels();
    MarkerPage marker1 = MarkerPage.snapshotPage(1);
    MarkerPage marker2 = MarkerPage.snapshotPage(2);
    // add 1 item to each buffer
    addPage(buffer, createPage(0), firstPartition);
    addPage(buffer, createPage(0), secondPartition);
    // broadcast 2 pages
    addPage(buffer, marker1, true);
    addPage(buffer, marker2, true);
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getBufferedPages).collect(Collectors.toList()), Arrays.asList(3, 3));
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getPagesSent).collect(Collectors.toList()), Arrays.asList(0L, 0L));
    // try to add one more page, which should block
    ListenableFuture<?> future = enqueuePage(buffer, createPage(3), firstPartition);
    assertFalse(future.isDone());
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getBufferedPages).collect(Collectors.toList()), Arrays.asList(4, 3));
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getPagesSent).collect(Collectors.toList()), Arrays.asList(0L, 0L));
    // get most elements
    assertBufferResultEquals(TYPES, getBufferResult(buffer, FIRST, 0, sizeOfPages(3), NO_WAIT), bufferResult(0, createPage(0), marker1, marker2));
    assertBufferResultEquals(TYPES, getBufferResult(buffer, SECOND, 0, sizeOfPages(3), NO_WAIT), bufferResult(0, createPage(0), marker1, marker2));
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getBufferedPages).collect(Collectors.toList()), Arrays.asList(4, 3));
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getPagesSent).collect(Collectors.toList()), Arrays.asList(0L, 0L));
    // we should still be blocked
    assertFalse(future.isDone());
    // acknowledge all pages
    buffer.get(FIRST, 3, sizeOfPages(3)).cancel(true);
    buffer.get(SECOND, 3, sizeOfPages(3)).cancel(true);
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getBufferedPages).collect(Collectors.toList()), Arrays.asList(1, 0));
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getPagesSent).collect(Collectors.toList()), Arrays.asList(3L, 3L));
    // finish the buffer
    assertFalse(buffer.isFinished());
    buffer.setNoMorePages();
    assertBufferResultEquals(TYPES, getBufferResult(buffer, FIRST, 3, sizeOfPages(1), NO_WAIT), bufferResult(3, createPage(3)));
    buffer.get(FIRST, 4, sizeOfPages(1)).cancel(true);
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getBufferedPages).collect(Collectors.toList()), Arrays.asList(0, 0));
    assertEquals(buffer.getInfo().getBuffers().stream().map(BufferInfo::getPagesSent).collect(Collectors.toList()), Arrays.asList(4L, 3L));
    assertFutureIsDone(future);
    buffer.abort(FIRST);
    buffer.abort(SECOND);
    assertQueueClosed(buffer, FIRST, 4);
    assertQueueClosed(buffer, SECOND, 3);
    assertFinished(buffer);
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MarkerPage(io.prestosql.spi.snapshot.MarkerPage) TestingTaskContext.createTaskContext(io.prestosql.testing.TestingTaskContext.createTaskContext) TaskContext(io.prestosql.operator.TaskContext) Test(org.testng.annotations.Test)

Aggregations

TaskContext (io.prestosql.operator.TaskContext)36 Test (org.testng.annotations.Test)24 TestingTaskContext (io.prestosql.testing.TestingTaskContext)12 RowPagesBuilder (io.prestosql.RowPagesBuilder)11 OperatorAssertion.toMaterializedResult (io.prestosql.operator.OperatorAssertion.toMaterializedResult)11 PlanNodeId (io.prestosql.spi.plan.PlanNodeId)11 MaterializedResult (io.prestosql.testing.MaterializedResult)11 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)11 DriverContext (io.prestosql.operator.DriverContext)10 TestingTaskContext.createTaskContext (io.prestosql.testing.TestingTaskContext.createTaskContext)7 DataSize (io.airlift.units.DataSize)6 OperatorContext (io.prestosql.operator.OperatorContext)5 OperatorFactory (io.prestosql.operator.OperatorFactory)5 PagesSpatialIndexFactory (io.prestosql.operator.PagesSpatialIndexFactory)5 PipelineContext (io.prestosql.operator.PipelineContext)5 SpatialIndexBuilderOperatorFactory (io.prestosql.operator.SpatialIndexBuilderOperator.SpatialIndexBuilderOperatorFactory)5 SpatialJoinOperatorFactory (io.prestosql.operator.SpatialJoinOperator.SpatialJoinOperatorFactory)5 QueryId (io.prestosql.spi.QueryId)5 MarkerPage (io.prestosql.spi.snapshot.MarkerPage)5 LocalExecutionPlan (io.prestosql.sql.planner.LocalExecutionPlanner.LocalExecutionPlan)5