blob: d4fdb8d73e7b7cc68c950c2d9666fb91dc13e17d [file]
/*
* Copyright 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.webgpu
import android.os.Process
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.webgpu.GPU.createGPUInstance
import androidx.webgpu.helper.WebGpu
import androidx.webgpu.helper.createWebGpu
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExecutorCoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeFalse
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class AsyncHelperTest {
private val dispatcher: CoroutineDispatcher = Executors.newSingleThreadExecutor { runnable ->
Thread(runnable, "Test-WebGPU-Thread")
}.asCoroutineDispatcher()
private val testScope = CoroutineScope(dispatcher)
private var processEventsJob: Job? = null
private lateinit var device: GPUDevice
private lateinit var webGpu: WebGpu
private val BASIC_SHADER = """
@vertex fn vertexMain(@builtin(vertex_index) i : u32) ->
@builtin(position) vec4f {
return vec4f();
}
@fragment fn fragmentMain() -> @location(0) vec4f {
return vec4f();
} """
@Before
fun setup(): Unit = runBlocking {
webGpu = createWebGpu(dispatcher)
device = webGpu.device
processEventsJob = testScope.launch {
webGpu.processEventsLoop()
}
}
@After
fun teardown() {
runBlocking {
processEventsJob?.cancelAndJoin()
}
if (::webGpu.isInitialized) {
webGpu.close()
}
testScope.cancel()
(dispatcher as? ExecutorCoroutineDispatcher)?.close()
}
@Test
fun asyncMethodTest() {
runBlocking {
webGpu.execute {
/* Set up a shader module to support the async call. */
val shaderModule = device.createShaderModule(
GPUShaderModuleDescriptor(shaderSourceWGSL = GPUShaderSourceWGSL(""))
)
val exception = assertThrowsSuspend(WebGpuException::class.java) {
/* Call an asynchronous method, converted from a callback pattern by a helper. */
device.createRenderPipelineAndAwait(
GPURenderPipelineDescriptor(vertex = GPUVertexState(module = shaderModule))
).close()
}
assertEquals(
"""Create render pipeline (async) should fail when no shader entry point exists.
The result was: ${exception.status}""",
CreatePipelineAsyncStatus.ValidationError,
exception.status
)
}
}
}
@Test
fun asyncMethodTestValidationPasses() {
runBlocking {
webGpu.execute {
/* Set up a valid shader module and descriptor */
val shaderModule = device.createShaderModule(
GPUShaderModuleDescriptor(shaderSourceWGSL = GPUShaderSourceWGSL(BASIC_SHADER))
)
/* Call an asynchronous method, converted from a callback pattern by a helper. */
@Suppress("UNUSED_VARIABLE")
val unused = device.createRenderPipelineAndAwait(
GPURenderPipelineDescriptor(
vertex = GPUVertexState(module = shaderModule), fragment = GPUFragmentState(
module = shaderModule,
targets = arrayOf(GPUColorTargetState(format = TextureFormat.RGBA8Unorm))
)
)
)
/* Create render pipeline (async) should pass with a simple shader.. */
}
}
}
private fun baseCancellationTest(doCancel: Boolean): Boolean {
val hasReturned = AtomicBoolean(false)
runBlocking {
webGpu.execute {
val shaderModule = device.createShaderModule(
GPUShaderModuleDescriptor(shaderSourceWGSL = GPUShaderSourceWGSL(BASIC_SHADER))
)
/* Launch the function in a new coroutine, giving us a job handle we can cancel. */
val job = launch {
@Suppress("UNUSED_VARIABLE")
val unused = device.createRenderPipelineAndAwait(
GPURenderPipelineDescriptor(
vertex = GPUVertexState(module = shaderModule),
fragment = GPUFragmentState(
module = shaderModule,
targets = arrayOf(GPUColorTargetState(format = TextureFormat.RGBA8Unorm))
)
)
)
hasReturned.set(true)
}
assumeFalse("The job completed before we could test it", hasReturned.get())
if (doCancel) {
job.cancel()
}
job.join()
}
}
return hasReturned.get()
}
/**
* Test that the async-based job will complete if it's not cancelled.
*/
@Test
fun asyncMethodCancellationTestControl() {
assertEquals(
"The async job should have completed but it failed to do so.",
true,
baseCancellationTest(false)
)
}
/**
* Test that the async-based job will not complete if it is cancelled.
*/
@Test
fun asyncMethodCancellationTest() {
assertEquals(
"The async job should have been cancelled but it completed.",
false,
baseCancellationTest(true)
)
}
private fun distinctShaderSource(seed: Int): String = """
@vertex fn vertexMain(@builtin(vertex_index) i : u32) ->
@builtin(position) vec4f {
return vec4f(${seed}.0, 0.0, 0.0, 1.0);
}
@fragment fn fragmentMain() -> @location(0) vec4f {
return vec4f(0.0, ${seed}.0, 0.0, 1.0);
} """
private fun assumeAsyncPipelineUsesWorkerThread() {
val isVulkan = runBlocking {
processEventsJob?.cancelAndJoin()
processEventsJob = null
webGpu.execute { webGpu.adapter.getInfo().backendType == BackendType.Vulkan }
}
assumeTrue("Async pipeline worker threads require the Vulkan backend", isVulkan)
}
@Test
fun asyncCallbackAttachesThreadWithKernelName() {
assumeAsyncPipelineUsesWorkerThread()
for (iteration in 1..2) {
val latch = CountDownLatch(1)
val callbackThreadName = AtomicReference<String>()
val callbackKernelComm = AtomicReference<String>()
val callbackError = AtomicReference<Throwable>()
runBlocking {
webGpu.execute {
val shaderModule = device.createShaderModule(
GPUShaderModuleDescriptor(shaderSourceWGSL = GPUShaderSourceWGSL(distinctShaderSource(iteration)))
)
device.createRenderPipelineAsync(
descriptor = GPURenderPipelineDescriptor(
vertex = GPUVertexState(module = shaderModule),
fragment = GPUFragmentState(
module = shaderModule,
targets = arrayOf(GPUColorTargetState(format = TextureFormat.RGBA8Unorm))
)
),
callbackExecutor = Executor(Runnable::run),
callback = object : GPURequestCallback<GPURenderPipeline> {
override fun onResult(result: GPURenderPipeline) {
try {
callbackThreadName.set(Thread.currentThread().name)
callbackKernelComm.set(
File("/proc/self/task/${Process.myTid()}/comm").readText().trim()
)
} finally {
result.close()
shaderModule.close()
latch.countDown()
}
}
override fun onError(exception: Exception) {
callbackError.set(exception)
shaderModule.close()
latch.countDown()
}
}
)
}
}
assertTrue("Timed out waiting for async pipeline callback", latch.await(10, TimeUnit.SECONDS))
assertNull("Unexpected callback error", callbackError.get())
assertEquals("DawnWorker", callbackThreadName.get())
assertEquals("DawnWorker", callbackKernelComm.get())
}
}
@Test
fun asyncCallbackForwardsUncaughtExceptionToHandler() {
assumeAsyncPipelineUsesWorkerThread()
val expectedMessage = "Uncaught async callback failure"
val handlerLatch = CountDownLatch(1)
val caughtThreadName = AtomicReference<String>()
val caughtThrowable = AtomicReference<Throwable>()
val previousHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
if (throwable.message == expectedMessage) {
caughtThreadName.set(thread.name)
caughtThrowable.set(throwable)
handlerLatch.countDown()
} else {
previousHandler?.uncaughtException(thread, throwable)
}
}
try {
runBlocking {
webGpu.execute {
val shaderModule = device.createShaderModule(
GPUShaderModuleDescriptor(shaderSourceWGSL = GPUShaderSourceWGSL(distinctShaderSource(101)))
)
device.createRenderPipelineAsync(
descriptor = GPURenderPipelineDescriptor(
vertex = GPUVertexState(module = shaderModule),
fragment = GPUFragmentState(
module = shaderModule,
targets = arrayOf(GPUColorTargetState(format = TextureFormat.RGBA8Unorm))
)
),
callbackExecutor = Executor(Runnable::run),
callback = object : GPURequestCallback<GPURenderPipeline> {
override fun onResult(result: GPURenderPipeline) {
result.close()
shaderModule.close()
throw IllegalStateException(expectedMessage)
}
override fun onError(exception: Exception) {
shaderModule.close()
}
}
)
}
}
assertTrue(
"Timed out waiting for UncaughtExceptionHandler",
handlerLatch.await(10, TimeUnit.SECONDS)
)
assertEquals("DawnWorker", caughtThreadName.get())
assertTrue(caughtThrowable.get() is IllegalStateException)
assertEquals(expectedMessage, caughtThrowable.get()?.message)
// Verify a subsequent async callback still succeeds on DawnWorker without pending-JNI state.
val followUpLatch = CountDownLatch(1)
val followUpThreadName = AtomicReference<String>()
runBlocking {
webGpu.execute {
val shaderModule = device.createShaderModule(
GPUShaderModuleDescriptor(shaderSourceWGSL = GPUShaderSourceWGSL(distinctShaderSource(102)))
)
device.createRenderPipelineAsync(
descriptor = GPURenderPipelineDescriptor(
vertex = GPUVertexState(module = shaderModule),
fragment = GPUFragmentState(
module = shaderModule,
targets = arrayOf(GPUColorTargetState(format = TextureFormat.RGBA8Unorm))
)
),
callbackExecutor = Executor(Runnable::run),
callback = object : GPURequestCallback<GPURenderPipeline> {
override fun onResult(result: GPURenderPipeline) {
followUpThreadName.set(Thread.currentThread().name)
result.close()
shaderModule.close()
followUpLatch.countDown()
}
override fun onError(exception: Exception) {
shaderModule.close()
followUpLatch.countDown()
}
}
)
}
}
assertTrue("Follow-up async callback timed out", followUpLatch.await(10, TimeUnit.SECONDS))
assertEquals("DawnWorker", followUpThreadName.get())
} finally {
Thread.setDefaultUncaughtExceptionHandler(previousHandler)
}
}
@Test
fun syncCallbackPropagatesUncaughtExceptionToCaller() {
val expectedMessage = "Synchronous callback failure"
val handlerInvoked = AtomicBoolean(false)
val previousHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
if (throwable.message == expectedMessage) {
handlerInvoked.set(true)
} else {
previousHandler?.uncaughtException(thread, throwable)
}
}
try {
createGPUInstance().use { instance ->
val thrown = assertThrows(IllegalStateException::class.java) {
instance.requestAdapter(
callbackExecutor = Executor(Runnable::run),
callback = object : GPURequestCallback<GPUAdapter> {
override fun onResult(result: GPUAdapter) {
result.close()
throw IllegalStateException(expectedMessage)
}
override fun onError(exception: Exception) {
throw IllegalStateException(expectedMessage, exception)
}
}
)
}
assertEquals(expectedMessage, thrown.message)
}
assertEquals(false, handlerInvoked.get())
} finally {
Thread.setDefaultUncaughtExceptionHandler(previousHandler)
}
}
}